Zesty Zesty - 1 month ago 21
Javascript Question

PHP-Insert Query Result into another Query Statement

I want to run these 3 queries together.
How do I fetch the Case_ID from the 2nd query to insert into the 3rd query's Case_ID ?

$query = "insert into `Case`(`informant_userid`,`CaseName`,`CaseTime`) values ('" . $informant_userid . "','" . $CaseName . "',now())";
$query = "SELECT `Case_ID` from `Case` ORDER BY `Case_ID` DESC LIMIT 1 ";
$query = "insert into Picture (Case_Pic,Case_ID) values ('" .addslashes($imagefile). "','" .$Case_ID"')" ;

Answer

I assume CaseID is an auto-increment column. Use LAST_INSERT_ID() to get the value that was assigned in the most recent INSERT.

$query = "insert into `Case`(`informant_userid`,`CaseName`,`CaseTime`) values ('" . $informant_userid . "','" . $CaseName . "',now())";
// execute $query
$query = "insert into Picture (Case_Pic,Case_ID) values ('" .addslashes($imagefile). "', LAST_INSERT_ID())" ;
// execute $query