Page 1 of 1

mysql_insert_id() returns 0

Posted: Thu Feb 03, 2011 3:26 pm
by nervino
Hi, I'm trying to use the mysql_insert_id() php function to have the last inserted id after an INSERT STATEMENT, but the function always returns 0 (zero).

- I have a table, "MyTable", with AUTO INCREMENT ID

- I make:
$query = 'INSERT INTO '.cms_db_prefix().'MyTable (a,b) VALUES ('a-value,'b-value')';
$dbr = $db->Execute($query)

hence:
$new_generated_id = mysql_insert_id();


The new record is correctly added to "MyTable" with the new id, but $new_generated_id is always 0.

Any suggestion?

thank you

Re: mysql_insert_id() returns 0

Posted: Thu Feb 03, 2011 4:33 pm
by nervino
Well, I tried this way and it works (but there is probably a better way...):

just after the execution of the INSERT QUERY:

Code: Select all

$dbr = $db->Execute($query)

		$q = "SELECT LAST_INSERT_ID()";
		$q_r = $db->Execute($q);

    while ($q_r && $rowq_r = $q_r->FetchRow())
      {
		$new_generated_id = ($rowq_r['LAST_INSERT_ID()']);
		}

Re: mysql_insert_id() returns 0

Posted: Thu Feb 03, 2011 4:55 pm
by Jos
You should do it like this

Code: Select all

$query = "INSERT INTO ".cms_db_prefix()."MyTable (a,b) VALUES (?,?)";
$dbr = $db->Execute($query, array($a-value,$b-value));

$insertid = $db->Insert_ID();

Re: mysql_insert_id() returns 0

Posted: Thu Feb 03, 2011 5:24 pm
by nervino
Thank you!