Jump to content

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


kaiman

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.