I'm trying to grab the id of the last inserted auto-increment row and cannot successfully grab it.
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$title = mysqli_real_escape_string($conxn,$_POST['blog_title']);
$entry = mysqli_real_escape_string($conxn,$_POST['blog_entry']);
$sourceName = mysqli_real_escape_string($conxn,$_POST['blog_source_name']);
$sourceLink = mysqli_real_escape_string($conxn,$_POST['blog_source_link']);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO blog (blog_title, blog_entry, blog_source, blog_link)
VALUES ('$title','$entry','$sourceName','$sourceLink')";
$lastID = $mysqli->insert_id;
if (!mysqli_query($conxn,$sql)) {
die('Error: ' . mysqli_error($conxn));
}
When I echo $lastID a "0" is returned after every submit.
You need to place the
$mysqli->insert_id()after the actualmysqli_query(). See below.That said, there are other issues with your code. First & foremost, you are mixing up the Object oriented style of calling
mysqli_*with the procedural style. For example the OOP method of$mysqli->real_escape_stringequates to the procedural method ofmysqli_real_escape_string.So this:
Should be this:
So without seeing the rest of your code, unclear how to handle. Know the difference & experiment. But here are my suggestions in good faith based on the code you have presented.
For example, your references to
$_POSTvalues do not have single quotes, so I added that. Also, since you are using double quotes—which handle string substitution—you can condense yourINSERTvariable setting by getting rid of the.concatenation.That done, this code chunklet can be cleaned up even more, and this is how I would handle it. I have made an array of the
$_POSTvalues you are grabbing so you don’t have to repeat code. Also added comments to make it clearer what is happening. And I have used the procedural format for all commands here. If OOP is what you want, then you need to change all of the commands to match OOP format.