phpmysqlmysqliinsert-id

Conversion from MySQL to mysqli not working


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


Solution

  • 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')");