We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

Newbie simple question - how do I get the ID of a record I've just inserted into the table in mysql using php?

RUSS_EMI
RUSS_EMI asked
on
Medium Priority
376 Views
Last Modified: 2013-12-12
I need the ID, so I can UPDATE other associated tables.

The book_table contains
ID key unique
Count
Book   unique
Description

The value I know is $NewBook
Thanks,
Russ
Comment
Watch Question

mysql_query("INSERT INTO books (id,count,book,description) values (null,5,'my book','blah blah blah')");
printf("Last inserted record id %d", mysql_insert_id());

i assume that your ID is autoincrement in which case i just pass in null to the insert query.
Is this working in mysql? Passing null value of autoincrement field? I think this must be done with omitting of id field from list of fields.

Author

Commented:
Jkna_gunn,
   Thank you, that works. But I also need the ID for an existing record where I know the $Book value.  Is that done the similarly, but using mysql_select_id() (after I do a SELECT query)?
Thanks
Russ

Commented:
Otherwise you can always get the next auto_index by the following statements

--code--

$sql = "SHOW TABLE STATUS LIKE \"tableName\"";
$result=execute($sql);
$rs=mysql_fetch_object($result);
mysql_free_result($result);
$nextID=$rs->Auto_increment;

--code--

The problem is that you have to lock the table before so that an other query doesn't take this id - I.E. unsuitable when there is a lot of inserting at the same time...

//jan

Author

Commented:
What I need, is to get an old, pre-existing ID value from a record when I know the unique Book value, but nothing else.
Russ

Commented:
Do you simply mean

SELECT id FROM table WHERE book=KnownBookValue

or did I misunderstand the question? =/

//jan

Author

Commented:
That's it.  But  can't seem to get ID number into a variable (ie. $BID)
Russ
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Thank you.  I'll assume that will work.  I hadn't done the reference to [0].
Russ
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.