0

Possible Duplicate:
PHP: how to get last inserted ID of a table?

I made a form and want to write data in two tables.

$sql = "INSERT INTO ma_forum (notcat_id, usr_id, not_titulo, not_status, not_tags, not_data, not_comentarios, not_resumo, not_texto) 

        VALUES('$categoria', '".$_SESSION[usr_name]."', '$titulo', '$status', '$tags', '".time()."', '$comentarios', '$resumo', '$texto')";

$res = mysql_query($sql) or die(mysql_error());

$sql_or = "INSERT INTO ma_forum_comentarios (comnot_habbo, comnot_data, comnot_status) VALUES('$_SESSION[usr_name]', '".time()."', '$status_comnot')";

$res = mysql_query($sql_or) or die(mysql_error());

But in the first table it writes the ID automatically auto_increment. But I would like to enter the ID of the first table and another column. Anyone know how to do?

Community
  • 1
  • 1

2 Answers2

1

Use the php function mysql_insert_id() to retrieve the last id inserted: http://php.net/manual/en/function.mysql-insert-id.php

So it should be:

$sql = "INSERT INTO ma_forum (notcat_id, usr_id, not_titulo, not_status, not_tags, not_data, not_comentarios, not_resumo, not_texto) VALUES ('$categoria', '".$_SESSION[usr_name]."', '$titulo', '$status', '$tags', '".time()."', '$comentarios', '$resumo', '$texto')";

$res = mysql_query($sql) or die(mysql_error());

$sql_or = "INSERT INTO ma_forum_comentarios (id, comnot_habbo, comnot_data, comnot_status) VALUES(" . mysql_insert_id() . ",'$_SESSION[usr_name]', '".time()."', '$status_comnot')";

$res = mysql_query($sql_or) or die(mysql_error());

Make sure you replace the 'id' column I specified with your actual id column name.

Software Guy
  • 3,190
  • 4
  • 21
  • 21
0
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
ejohansson
  • 2,832
  • 1
  • 23
  • 30