note 102464 deleted from function.mysql-insert-id by danbrown

[email protected] Wed, 16 Feb 2011 07:10:02 -0800
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: Anonymous 

----

I just wrote a function, which returns the last inserted auto-incrementing id:

<?php
$r = mysql_query("INSERT INTO `my_table` (...) VALUES (...)");
$id = last_insert_id( $r );
if( false === $id) echo 'error';

function last_insert_id_after_single_insert( $r ){
  if( true !== $r) return false;
  if( 1 !== mysql_affected_rows()) return false;

  $r = mysql_query("SELECT LAST_INSERT_ID() AS `id`"); // INSERT returns true/false
  if( 1 !== mysql_num_rows( $r )) return false;  // false or other num

  $r = mysql_fetch_array( $r );
  if( false === $r) return false;

  return $r['id'];
}
?>