0

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

Mauro74
  • 4,686
  • 15
  • 58
  • 80
  • "It doesn't work" is insufficient information. what debugging have you done? What, exactly, isn't working? – Donnie May 31 '10 at 23:10

4 Answers4

2

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.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
1

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().

Savageman
  • 9,257
  • 6
  • 40
  • 50
1

Try mysql-insert-id instead.

a1ex07
  • 36,826
  • 12
  • 90
  • 103
0

As the name says, mysql_fetch_array($select_author) returns an array so you will need to get the specific value in that array to insert in the other table.

jeroen
  • 91,079
  • 21
  • 114
  • 132