I need the id of the last inserted object. I use prepared statements to avoid sql injection. But i'm not sure how to obtain the id.
$sql = "INSERT IGNORE INTO faculty (id, term, role, prefix, first_name,
middle_name, last_name, suffix) VALUES (?,?,?,?,?,?,?,?)";
if (!($stmt = $mysqli->prepare($sql)))
echo "Faculty Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
$stmt->bind_param('sissssss',
$faculty['id'],
$faculty['term'],
$faculty['role'],
$faculty->name->prefix,
$faculty->name->first,
$faculty->name->middle,
$faculty->name->last,
$faculty->name->suffix
);
if (!$stmt->execute())
echo "Faculty Execute failed: (" . $mysqli->errno . ") " . $mysqli->error;
$result = $stmt->insert_id;
echo "\n Result:" . $result;
$stmt->close();
The result is 0 always despite there being an entry in the database
Solution The element was being inserted into the database. The problem was when I had created the table id wasn't an integer it was a varchar which represented an employee id. To fix this, i added the employee id as an additional column in the table and used the default id int auto_increment primary key and it worked.
There's also a function to simply free the memory associated with the MySQLi result and prepared statement, respectively: $result->free() and $stmt->free() .
If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.
You must always use prepared statements for any SQL query that would contain a PHP variable. To do so, always follow the below steps: Create a correct SQL SELECT statement. Test it in mysql console/phpmyadmin if needed.
" $stmt " obviously (I think) stands for "statement". As a variable name it's arbitrary, you can name that variable anything you want. $stmt is just rather idiomatic. A prepared statement as such is a database feature.
Try changing $result = $stmt->get_result();
to $result = $stmt->insert_id;
get_result()
is more for SELECT
queries, rather than INSERT
s.
http://php.net/manual/en/mysqli-stmt.get-result.php
http://php.net/manual/en/mysqli-stmt.insert-id.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With