I am new to PHP and MySQL. I am getting the last ID used for an insert using insert_id. How do I (or can I?) store that value to a variable so I can continue to use it (to persist a session, to look up other data, etc.)? Here is my code:


$result = $conn->query("insert into user (passwd, email) values (sha1('$password'), '$email')");

echo 'ID of new inserted row is : '.$conn->insert_id; //this works to print out the last ID

$lastid = $conn->insert_id(); //my code errors here
echo $lastid;


$conn is my mysqli connection. Everything works except the last 2 lines. What am I doing wrong? I have tried the documentation, google, etc.

Thanks so much in advance!!!

    Look at the line that works, then look at the line that doesn't work. They aren't the same - you've added something to the line that doesn't work (which, incidentally, makes it not work...)

    (HINT: "insert_id" is not the name of a method/function!)

      I use the "Brute Force" method, a select after the insert to make sure I have the correct autoincrement index:

      --ETA: Due to race condition of many users signing up at once...

      			// <snip>....Everything to this point looks good.  We insert the users information into
      			//user_tbl - we then query that table to get the autonumber customer id.  This id
      			//is entered into the URL that is emailed to the user to validate his account.
      			$newuser = "INSERT INTO `user_tbl` (`username`,`password`,`email`,`groupid`,`validated`) VALUES ('".$username."','".$password."','".$email."',3,'".$random."');";
      			$newexec = mysql_query($newuser);
      
      $newuser = "SELECT * FROM user_tbl WHERE username = '".$username."' AND password = '".$password."';";
      			$newexec = mysql_query($newuser);
      			if (mysql_num_rows($newexec)) {
      
      /// </snip>
      

        Thank you so much. Removing the () solved my problem. I can't believe I did that. :o

        troybtj, I wonder how likely using my method instead of yours to get the id is to cause a problem. This is not going to be a super-high volume website. I can't see getting more than a few hundred registrations at once, and maybe only after the initial email blast/mail drop. Any input?

        Thanks again, bradgrafelman!

        Corrected code, just in case anyone else is searching:


        echo 'ID of new inserted row is : '.$conn->insert_id; // this works to print out the value
        $lastid = $conn->insert_id; // this now gets the value
        echo 'value of lastid is : '.$lastid; // and prints it out as well


          Your method using a class shouldn't be an issue, since it is all in the same transaction, I'm sometimes just overly paranoid on some items. Carryover from 80's learning/methods.

            Thanks for the input. Some paranoia is definitely good in this field. Thanks again.

              Write a Reply...