-1

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;
AStopher
  • 4,207
  • 11
  • 50
  • 75
Steward
  • 1
  • 3

2 Answers2

3

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

Community
  • 1
  • 1
Indra Kumar S
  • 2,818
  • 2
  • 16
  • 27
0
 $query = "INSERT INTO .......";
 $mysqli->query($query);
 printf ("New Record has id %d.\n", $mysqli->insert_id);

More Info

Priyank
  • 3,778
  • 3
  • 29
  • 48