Last Id mysql_insert_id 与其他查询

Last Id mysql_insert_id with an other query

$query = mysql_query(
  "insert into users (id,email,password,firstname,lastname) 
  values ('','$email','$password','$firstname','$lastname')"
) or die(mysql_error());

echo $userid = mysql_insert_id();

$q_query = mysql_query(
  "insert into qualification (q_id) values ('$userid')"
) or die(mysql_error());

echo $userid 显示完美,但该行未插入 qualification table。为什么不呢?

我怀疑@Gil 的答案是正确的。然而,使用 mysql 函数 last_insert_id() 是一种更直接的方法:

mysql> create temporary table users (id int unsigned not null auto_increment primary key, email text, password text, firstname text, lastname text);
Query OK, 0 rows affected (0.00 sec)

mysql> insert into users (id,email,password,firstname,lastname) values ('','dan@site.com', 'password','dan','f');
ERROR 1366 (HY000): Incorrect integer value: '' for column 'id' at row 1

这取决于你是否处于严格模式(感谢下面的评论)

mysql> insert into users (id,email,password,firstname,lastname) values (null,'dan@site.com', 'password','dan','f');
Query OK, 1 row affected (0.00 sec)

mysql> create table qualification (q_id int unsigned not null);
Query OK, 0 rows affected (0.02 sec)

mysql> insert into qualification( q_id) values (last_insert_id() );
Query OK, 1 row affected (0.00 sec)

mysql> select * from users,qualification;
+----+--------------+----------+-----------+----------+------+
| id | email        | password | firstname | lastname | q_id |
+----+--------------+----------+-----------+----------+------+
|  1 | dan@site.com | password | dan       | f        |    1 |
+----+--------------+----------+-----------+----------+------+
1 row in set (0.00 sec)