1

I most recently came across ezSQL and thought it's pretty cool.

Based on the tutorial, I perform the following to create a new row:

$db->query(“INSERT INTO users (name) VALUES ('Amy')”) ;

How do i retrieve the id ( assuming auto-increment ) for the above query ?

THanks!

DjangoRocks
  • 13,598
  • 7
  • 37
  • 52

2 Answers2

4

According to the documentation, the ID should be accessible with $db->insert_id

TiiJ7
  • 3,332
  • 5
  • 25
  • 37
  • Please note that if you have a space before `INSERT` or a line break in your code for ex. ` $db->query(“ INSERT INTO users (name) VALUES ('Amy')”) ;` `$db->insert_id` return nothing. In ezSQL you should remove any space or line breaks in query before `INSERT` clause. – ewroman Jul 13 '15 at 13:51
4

The return value of your executed query is number of rows that were effected, while the insert id can be found by $db->insert_id.

So the code should be like:

$result = $db->query(“INSERT INTO users (name) VALUES ('Amy')”) ;
if($result){
  $insert_id = $db->insert_id;
}else{
  echo "Row could not be inserted.";
}
  • $result value will be 1, which displays the number of rows that were inserted in to database.
  • $insert_id is the id that you are looking for!
Fiaz Husyn
  • 171
  • 2