View Single Post

   
  #2 (permalink)  
Old 02-28-2008, 10:07 AM
Jerry Stuckle
 
Posts: n/a
Default Re: Can I determine the index (value) of an auto-increment field

eholz1 wrote:
> Hello MYSql Lovers,
>
> Is there a handy way (using PHP) to determine the value of an auto-
> increment field when I am going to
> insert a record into a table?
>
> by this I mean, without counting the records in the table already and
> adding 1? or using MAX(id) + 1 ,etc?
>
> A more challenging question (for me at least), suppose I have an empty
> table with an auto-increment field (id),
> and I am going to insert all the files in a given directory in the the
> database table, at insert time, is there a way I can predict (or know)
> the value of "id"??
>
> I would like to create a value in another field based on the value (a
> number) of the id field.
> Like col1 value = id + (MOD %30 of id).
>
> I know that i can load the table first, then do an update on col1
> using the formula based on the value of "id".
>
> I was wondering if there was a better way, etc.
>
> thanks
> eholz1
>


Sorry, you can't reliably predict the value of the last insertid before
the row is inserted. For instance - what if you had two connections
inserting concurrently? Both could "predict" the same id, but only one
would get it.

Of course you can use mysql_insert_id() to get the last id inserted.
However, it might be easier to fetch the first id you insert, then run
one SQL statement to update all rows after that one, i.e.

(insert row)
$start = mysql_insert_id();
(insert more rows)
$result = mysql_query("UPDATE mytable " .
"SET col1=MOD(id, 30)" .
"WHERE id >= " . id);

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================
Reply With Quote