0

I am in a process of converting my Existing MySQL to mysqli

But I can't get this piece of code correct

mysql_query("INSERT INTO `sendmsg`(`sendname`, `recievename`, `subject`, `body` , `mdate`, `mtime`) VALUES ('$sendname','$recievename','$subject','$body','$msgdate','$msgtime')");
$new_id = mysql_insert_id();
mysql_query("INSERT INTO `recievemsg`(`msgid`, `sendname`, `recievename`, `subject`, `body`, `mdate`, `mtime`, `status`) VALUES ($new_id,'$sendname','$recievename','$subject','$body','$msgdate','$msgtime','UNREAD')");

What I tried is given below but didn't work

$mysqli->query("INSERT INTO `sendmsg`(`sendname`, `recievename`, `subject`, `body` , `mdate`, `mtime`) VALUES ('$sendname','$recievename','$subject','$body','$msgdate','$msgtime')");
$new_id = mysqli_insert_id();
$mysqli->query("INSERT INTO `recievemsg`(`msgid`, `sendname`, `recievename`, `subject`, `body`, `mdate`, `mtime`, `status`) VALUES ($new_id,'$sendname','$recievename','$subject','$body','$msgdate','$msgtime','UNREAD')");

The Problem is with the $new_id = mysqli_insert_id(); statement bcoz the first query is executing

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sharan Mohandas
  • 861
  • 1
  • 9
  • 25
  • Since you're upgrading to `mysqli`, you should take the time to familiarise yourself with parameter binding and prepared statements. – scrowler Jun 27 '14 at 04:46
  • Procedural style `mysqli_*` functions need the connection variable passed into them, unlike `mysql_*` or the object orientated version of `mysqli` – scrowler Jun 27 '14 at 04:47
  • Could you provide me a link to detailed tutorial on how to convert from mysql to mysqli.. I couldnt get a good one – Sharan Mohandas Jun 27 '14 at 04:55
  • the [PHP manual](http://php.net/mysqli) has everything you'll need to know – scrowler Jun 29 '14 at 23:36
  • Does this answer your question? [How to change mysql to mysqli?](https://stackoverflow.com/questions/1390607/how-to-change-mysql-to-mysqli) – Dharman Jul 10 '21 at 12:34

1 Answers1

2

For mysqli Object oriented style to get the last inserted id use this

$mysqli->insert_id ;

http://www.php.net/manual/en/mysqli.insert-id.php

So your queries will be as

$mysqli->query("INSERT INTO `sendmsg`(`sendname`, `recievename`, `subject`, `body` , `mdate`, `mtime`) VALUES ('$sendname','$recievename','$subject','$body','$msgdate','$msgtime')");

$new_id = $mysqli->insert_id;

$mysqli->query("INSERT INTO `recievemsg`(`msgid`, `sendname`, `recievename`, `subject`, `body`, `mdate`, `mtime`, `status`) VALUES ($new_id,'$sendname','$recievename','$subject','$body','$msgdate','$msgtime','UNREAD')");
Abhik Chakraborty
  • 44,654
  • 6
  • 52
  • 63