I am trying to get last query insert id.but my code always return zero.
My Code
private function Cnn() { return mysqli_connect('localhost','root','root','db'); } protected function MyCommandInsertId($sql) { if(mysqli_query($this->Cnn(),$sql)) { return mysqli_insert_id($this->Cnn()); } $this->err = mysqli_error($this->Cnn()); return false; } public function Insert() { $sql = "insert general_info(name,email,password) values('".$this->ms($this->name)."','".$this->ms($this->email)."','".md5($this->password)."')"; //print''.$sql.''; $last_insert_id=$this->MyCommandInsertId($sql); }
here return mysqli_insert_id($this->Cnn());
always return zero
Advertisement
Answer
Please check the definition of mysqli_insert_id
:-
The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) used in the last query.
It means either column in your table that have AUTO_INCREMENT
value is not exist.
Or
No insertion of data happen programmatically on your table in the curren program flow. Since no insert query is fired in your code, it returned Zero.
Note:- Just do an insert query first in your code and then check what is the output given by mysqli_insert_id
. Then you can understand easily what i am trying to say.Thanks
A working example of my local is here:-
<?php error_reporting(E_ALL); ini_set('display_errors',1); function Cnn() { $conn = mysqli_connect('localhost','root','','stack'); return $conn; } function MyCommandInsertId($sql) { $conn = Cnn(); if(mysqli_query($conn,$sql)) { $lastid = mysqli_insert_id($conn); return $lastid; }else{ $err = mysqli_error($conn); return $err; } } function Insert() { $sql = "INSERT INTO bom(bom_description,product_id,finish_product,bom_quantity,UOM) values('Table cleaner','','','','')"; $st_insert_id = MyCommandInsertId($sql); echo $st_insert_id; } Insert(); ?>
Output:- http://prntscr.com/9u2iyv (inserted id) and http://prntscr.com/9u2j6i(table view after insertion)