Hello I am trying to use php to insert an object into a MySql table and then get the Id of the newly created object but i can not figure out why it is not working. Here is what i have:
$query = "INSERT INTO `".$Table."` (`ID`) VALUES (NULL);";
$resultset = mysql_query($query, $connection);
$query = "SELECT LAST_INSERT_ID() INTO @".$Table.";";
$resultset = mysql_query($query, $connection);
echo mysql_fetch_assoc($resultset);
The insert works great but I am just getting an empty value where I should be getting the Id. Thanks!
New Code:
$query = "INSERT INTO `".$Table."` (`ID`) VALUES (NULL); ";
$resultset = mysql_query($query, $connection);
$id = mysql_insert_id();
echo $id;
Just after executing first query you have to use the function that i tell you:-
$id = mysql_insert_id();
And then change your second query LAST_INSERT_ID() to $id.
Note:- please take care of double and single quote at the time using $id in second query.
Also mysql_* is officially deprecated now. Use mysqli_* or PDO for this purpose.
This SQL query:
SELECT LAST_INSERT_ID() INTO @Something;
doesn't return a resultset. (It does set the variable.) So, your fetch_assoc statement doesn't get anything back.
If you want the id in the resultset do this.
SELECT LAST_INSERT_ID();
Or, use the mysql_insert_id() function.