I have 2 queries and i want to use result of first query in second one.
Following does not work for me:
$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);
Is there any other way to get same result?
You could have used MySQL LAST_INSERT_ID() function. This way all this mess with insert id will be gone.
$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
contains an SQL resource, not the id.
$insert_id = mysql_insert_id();
$sql = "INSERT INTO tbl_ms(m_name, ng_ID, status)
VALUES ($app_id, $insert_id, 1)";
Don't forget to sanitize user input to avoid injection attacks.
$result
in your code will always contain a boolean, and if it was successful, when used in the next query, this will always be 1
. You echo
d the value you need, but you didn't catch it in a variable so it could be used in the next query.
Try this:
$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());
You MUST escape user input before using it in a query - you don't want a visit from Bobby Tables ...
Make a variable $insertedID = mysql_insert_id();
just before the second $sql
variable ! And in the second $sql
query replace the $result
with $insertedID
It should solve your problem !
In the second query just use
insert into tbl_ms(m_name, ng_ID, status)
values ($app_id,last_insert_id() ,1)
no need to play this via PHP!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.