如何在单个php准备好的语句上同时使用SELECT和INSERT查询?

时间:2019-09-22 04:04:28

标签: php mysql prepared-statement

我正在尝试插入一条记录,并使用准备好的语句获取该记录的ID。为此,我编写了一个查询"INSERT INTO ". $natureFlight ."(typeFlight, dateTimeSubmit, emb, acType, reg, companyName, callSign, dateFlight) VALUES (?,?,?,?,?,?,?,?); SELECT LAST_INSERT_ID();",该查询在MySQL控制台中运行良好,但无法使用已准备好的语句运行。如果我从查询中删除SELECT LAST_INSERT_ID();,则它可以使用准备好的语句插入记录。

我搜索了解决方案,但发现了this,但不适用于我。

这是一个代码

$natureFlight = $_POST['selectedNatureFlight'];
$typeFlight = $_POST['selectedTypeFlight'];
$dateTimeSubmit = $_POST['dateTime'];
$emb = $_POST['emb'];
$acType = $_POST['acType'];
$reg = $_POST['reg'];
$companyName = $_POST['companyName'];
$callSign = $_POST['callSign'];
$dateFlight = $_POST['dateFlight'];

$insertRecord = "INSERT INTO ". $natureFlight ."(`typeFlight`, `dateTimeSubmit`, `emb`, `acType`, `reg`, `companyName`, `callSign`, `dateFlight`) VALUES (?,?,?,?,?,?,?,?); SELECT LAST_INSERT_ID();";
$stmt = $conn->prepare($insertRecord);
$stmt->bind_param("ssssssss", $typeFlight, $dateTimeSubmit, $emb, $acType, $reg, $companyName, $callSign, $dateFlight);
if($stmt->execute()){
    $stmt->bind_result($id);
    while($stmt->fetch()) {
         echo $id;
        }           
} else{
    $res['error'] = true;
    $res['message'] = $stmt->error;
}

运行此命令后出现错误

Fatal error: Uncaught Error: Call to a member function bind_param() on bool in
D:\xampp\htdocs\test\proc\flightPDF\src\body\user\records.php:40 Stack trace: #0 {main} thrown in 
D:\xampp\htdocs\test\proc\flightPDF\src\body\user\records.php on line 40

第40行包含$stmt->bind_param("ssssssss", $typeFlight, $dateTimeSubmit, $emb, $acType, $reg, $companyName, $callSign, $dateFlight);

2 个答案:

答案 0 :(得分:1)

您不能准备多个语句。这就是为什么您的准备失败并且$stmt是一个布尔值(false)的原因。要解决此问题,请从SELECT LAST_INSERT_ID()查询中删除INSERT并将代码更改为此,使用insert_id获得最后的插入ID:

$insertRecord = "INSERT INTO ". $natureFlight ."(`typeFlight`, `dateTimeSubmit`, `emb`, `acType`, `reg`, `companyName`, `callSign`, `dateFlight`) VALUES (?,?,?,?,?,?,?,?)";
$stmt = $conn->prepare($insertRecord);
$stmt->bind_param("ssssssss", $typeFlight, $dateTimeSubmit, $emb, $acType, $reg, $companyName, $callSign, $dateFlight);
if (!$stmt) {
    $res['error'] = true;
    $res['message'] = $conn->error;
}
elseif ($stmt->execute()) {
    echo $conn->insert_id;
} 
else {
    $res['error'] = true;
    $res['message'] = $stmt->error;
}

答案 1 :(得分:0)

使用lastInsertId代替SELECT语句

$last_id = $conn->lastInsertId;

希望这会为您提供帮助.. !!