Jump to content

Is this the best way to use mysql_insert_id() or do I need to SELECT it?


Recommended Posts

I have two tables. The first with an auto-increment field of id and the second with a article_id field. I want to get the value of the auto-increment field in the first table and insert it into the article_id field of the second table (so they match). I am using the mysql_insert_id() command for the first time and I am wondering if I can run a query like this and turn it into a variable or if I need to use a SELECT query from the the mysql_insert_id() field from the first table before inserting it into the second table?

 

Any feedback is appreciated.

 

Thanks,

 

kaiman

 

Here is what I have so far (untested):

 

// insert data into blog database
$sql1="INSERT INTO $tbl_name1(author, title, content, date)VALUES('$author', '$title', '$content', NOW()) LIMIT 1";
$result1=mysql_query($sql1) or trigger_error("A mysql error has occurred!");
$article_id = mysql_insert_id ();

// if successfully inserted data into database, redirect user
if($result1){
header( "Location: http://www.mydomain.com/blog/add/success/" );
}
else {
header( "Location: http://www.mydomain.com/blog/add/error/" );
exit;
}

// insert data into blog categories database
$sql2="INSERT INTO $tbl_name2(article_id, category)VALUES('$article_id', '$category' LIMIT 1";
$result2=mysql_query($sql2) or trigger_error("A mysql error has occurred!");

// if successfully inserted data into database, redirect user
if($result2){
header( "Location: http://www.mydomain.com/blog/add/success/" );
}
else {
header( "Location: http://www.mydomain.com/blog/add/error/" );
exit;
}

@ Pikachu2000. OK thanks. I was just wondering whether I had the syntax/query structure correct or not. Unfortunately, I have no DB connection at the moment. I will give it a shot when I do and let you know if I have trouble.

 

Thanks again,

 

kaiman

One more thing, is there a way to tie these if else statements together? Rather then having two could I do something like:

 

if($result1,$result2){
header( "Location: http://www.mydomain.com/blog/add/success/" );
}
else {
header( "Location: http://www.mydomain.com/blog/add/error/" );
exit;
}

 

Thanks,

 

kaiman

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.