我有一个MySQL表,名为war_engagement
,它有一个自动递增id(名为w_e_id
)作为主键。我正在插入像这样的记录
//insertion in first table
$query = "INSERT INTO war_engagement (
`attacker_user_id` ,
`attacker_city_id` ,
`attacker_mode` ,
`result`
)
VALUES (
'$_SESSION[user_id]',
'$cur_city_id',
'default',
''
)";
$rs = mysql_query($query) or die(mysql_error()." in query $query");
如果上面的查询成功执行,那么我想将这个最近插入的自动递增id(即w_e_id
)作为外键插入另一个名为war_engagement_troops
的表中
//if first record inserted successfully then insert second table
if($rs)
{
echo "'".$sending_troop."' ,";
$query = "INSERT INTO war_engagement_troops (
`w_e_id` ,
`quantity` ,
`expired`
)
VALUES (
'$recently_inserted_w_e_id',
'$quantity',
'$expired'
)";
$rs = mysql_query($query) or die(mysql_error()." in query $query");
if(!$rs) echo $rs;
}
我想得到w_e_id
(它是自动递增的),把它分配给$recently_inserted_w_e_id
。
(我也使用MAX(w_e_id)来检索最大id,但它看起来不是理想的方式,并且可能会在多个用户插入中混合)。
请给我一些理想的解决方案,以获得最近插入的id/记录。
您可以使用mysql_insert_id()函数获取最后插入的id,然后将其用作另一个表的foregin键
您正在寻找mysql_insert_id()函数。但我强烈建议您使用PDO
$recently_inserted_w_e_id = mysql_insert_id();
如果您不想使用MAX(w_e_id),那么在INSERT语句之后,您可以使用
SELECT LAST_INSERT_ID();
我们可以使用mysql_insert_id();功能以及
它看起来像这个
$query = "INSERT INTO war_engagement ( `w_e_id` , ...) VALUES ( ...);
//if first record inserted successfully then insert second table
if($rs)
{
$query = "INSERT INTO war_engagement_troops ( `id` , `w_e_id` , ...) VALUES ( '', LAST_INSERT_ID(), ....)";
}
如果使用面向对象风格的,则可以使用mysqli_insert_id()函数或mysqli::$insert_id
http://php.net/manual/en/mysqli.insert-id.php
如果使用PDO,请使用方法PDO::lastInsertId()
http://php.net/manual/en/pdo.lastinsertid.php
SELECT TOP 1 w_e_idFROM war_engagement订单依据w_e_id desc