简体   繁体   中英

php retrieving id of the last record inserted and insert it in another table

I'm trying to retrieve the id of the last record inserted in the table 'authors' and insert the retrieved id in the 'articles' table; here's my code:

$title = mysql_real_escape_string($_POST[title]);
$body = mysql_real_escape_string($_POST[body]);
$category = mysql_real_escape_string($_POST[category]);

$insert_author="INSERT INTO authors (name) VALUES ('$title')";
$select_author= mysql_query("SELECT LAST_INSERT_ID()");

$authId = mysql_fetch_array($select_author);
$query="INSERT INTO articles (body, date, category, auth_id) VALUES ('$body', '$date_now', '$category', '$authId')";

this doesn't work...

Any idea please?

Thanks in Advance

Mauro

You can get the last insert id with mysql_insert_id()

$insert_author="INSERT INTO authors (name) VALUES ('$title')";
mysql_query($insert_author) or die(mysql_error());

$authId = mysql_insert_id();

$query="INSERT INTO articles (body, date, category, auth_id) VALUES
('$body', '$date_now', '$category', '$authId')";

Note that you were missing mysql_query function for insert query, i have added that also in code above.

What exactly doesn't work. Do the $authId contains the expected value? Did you dump it to check?

Apart from that, you forgot the second mysql_query() .

请尝试使用mysql-insert-id

顾名思义, mysql_fetch_array($select_author)返回一个数组,因此您将需要获取该数组中的特定值以插入另一个表中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM