I don't know, what's wrong in my code. I try to get the latest insert id, it's echoing 0. Any idea?
public function __construct() {
$this->mysqli = new mysqli(MYSQLI_SERVER, MYSQLI_USER, MYSQLI_PWD, MYSQLI_DBNAME) or die ('Error with connecting to the database!');;
}
public function insert_id(){
return $this->mysqli->insert_id;
}
$db->query("INSERT INTO user(f_name, l_name) VALUES('$f_name', '$l_name')");
var_dump($db->insert_id()); // return 0?
Definition and Usage If you have a table with an AUTO_INCREMENT attribute for a column and, if your last MySQLi function call executes INSERT or UPDATE statement. The mysqli_insert_id() function returns the auto generated id of the last executed query.
The mysqli_insert_id() function / mysqli::$insert_id returns the id (generated with AUTO_INCREMENT) used in the last query. Return value: The value of the AUTO_INCREMENT field that was updated by the previous query.
The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) from the last query.
If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.
You should use it as follow:
<?php
$mysqli = new mysqli(SQLI_SERVER, MYSQLI_USER, MYSQLI_PWD, MYSQLI_DBNAME);
if ($result = $mysqli->query("INSERT INTO user(f_name, l_name) VALUES('$f_name', '$l_name');")) {
echo 'The ID is: '.$mysqli->insert_id;
}
?>
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