How to get previous AUTO_INCREMENT_ID

nassausky

Member
I am stuck to this forum like glue :)

New question. How might I get the auto_increment_id of the previous insert operation I made. I tried using mysql_insert_id() but it's returning zero (0).

In business_logic.php:

[pre]
$sql = "INSERT INTO mytable ('name') VALUES ('vinny')";
$result = execute_db($sql, $conn);
echo "ID of last inserted record is: " . mysql_insert_id();
[/pre]


Output:

[pre]
ID of last inserted record is: 0
[/pre]
 

nassausky

Member
Until someone has a solution to the problem I am temporarily using another method to find the last auto_increment_id.

I added the following code :


[pre]
// The following sql query will sort my table by my primary key field in reverse order and outputing only the last 1
$sql="select ".$key_field." from ".$table." order by ".$key_field." desc limit 1;";
foreach ($conn->query($sql) as $row) {
$new_id=$row['myPrimaryKeyField'];
}
//now this $new_id i can pass to an update function after I create a new record/row
[/pre]
 

eugenio

Administrator
Staff member
Hello,
if you are using MySQL you can use this abstract function provided by dadabik

$id = get_last_ID_db();

just after your execute_db;

Cheers.
 
Top