Mysqli insert_id ()

I do not know what happened in my code.? I'm trying to get the last insert id, is its echo 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? 
+6
source share
2 answers

You should use it as follows:

 <?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; } ?> 
+11
source

The mysqli_insert_id () function returns the identifier generated by the query in the table with a column that has the AUTO_INCREMENT attribute. If the last query was not an INSERT or UPDATE statement, or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.

It looks like you do not have a field with the AUTO_INCREMENT attribute or if you have one that you are not using in the request.

+5
source

Source: https://habr.com/ru/post/887025/


All Articles