简体   繁体   中英

How do I get the ID of an inserted row?

I have this following example query, which works - I CAN insert values into my MySQL table, which also includes an unique id column. I want to get the id from the inserted row, after I execute the query. However what I get is 0 every time ($gotId=0) .

What am I doing wrong?

 $stmt = $conn->prepare("INSERT INTO ....... ");                                
 $stmt-> bind_param("ss", ....);
 $stmt->execute();      
 $gotId = $conn->insert_id;

Full query:

$conn = $db->connect(); 
$stmt = $conn->prepare("INSERT INTO table(value1, value2) VALUES(?, ?)");                               
$stmt-> bind_param("ss", $value1, $value2);
$stmt->execute();       
$gotId = $conn->insert_id;

After calling the execute() method on the PreparedStatement , the id of the insert row will be in the insert_id attribute Only read it.

$stmt->execute(); 
$gotId = $stmt->insert_id;

Taken from here

 $query = "INSERT INTO .......";
 $mysqli->query($query);
 printf ("New Record has id %d.\n", $mysqli->insert_id);

More Info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM