[英]Running two SQL queries in PHP where the first statement creates a temporary table to be used by the second one
[英]How to launch two sql queries using result of first one in second?
我有2个查询,我想在第二个中使用第一个查询的结果。
以下对我不起作用:
$id = $_GET['uid'];
$app_id = $_GET['apid'];
$sql = "insert into tbl_sc (client_id,status) values ($id,1)";
mysql_query($sql) or die ($sql);
$result = mysql_insert_id();
echo $result;
$sql = "insert into tbl_ms(m_name, ng_ID, status)
values ($app_id,$result ,1)";
$result = mysql_query($sql) or die ($sql);
还有其他方法可以得到相同的结果吗?
您可能已经使用过MySQL LAST_INSERT_ID()函数。 这样,所有带有插入ID的混乱都将消失。
$sql = "insert into tbl_sc (client_id,status) values ($id,1)";
if(mysql_query($sql)){
$sql = "insert into tbl_ms(m_name, ng_ID, status)
values ($app_id, LAST_INSERT_ID() ,1)";
$result = mysql_query($sql);
if($result){
// Process your result
}else{
// second query failed!
die (mysql_error());
}
}else{
// first query failed!
die (mysql_error());
}
$result
包含一个SQL资源,而不是ID。
$insert_id = mysql_insert_id();
$sql = "INSERT INTO tbl_ms(m_name, ng_ID, status)
VALUES ($app_id, $insert_id, 1)";
不要忘记清理用户输入,以避免注入攻击。
代码中的$result
始终包含一个布尔值,如果成功,则在下一个查询中使用时,该值始终为1
。 您echo
了所需的值,但没有将其捕获到变量中,因此可以在下一个查询中使用它。
尝试这个:
$id = mysql_real_escape_string($_GET['uid']);
$sql = "INSERT INTO tbl_sc
(client_id, status)
VALUES
($id, 1)";
mysql_query($sql) or die ("MySQL error with query ( $sql ): ".mysql_error());
$app_id = mysql_real_escape_string($_GET['apid']);
$insertId = mysql_insert_id();
$sql = "INSERT INTO tbl_ms
(m_name, ng_ID, status)
VALUES
($app_id, $insertId ,1)";
mysql_query($sql) or die ("MySQL error with query ( $sql ): ".mysql_error());
在查询中使用用户输入之前, 必须先对其进行转义-您不希望Bobby Tables进行访问...
创建一个变量$insertedID = mysql_insert_id();
就在第二个$sql
变量之前! 在第二个$sql
查询中,将$result
替换为$insertedID
它应该解决您的问题!
在第二个查询中,只需使用
insert into tbl_ms(m_name, ng_ID, status)
values ($app_id,last_insert_id() ,1)
无需通过PHP玩!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.