为什么当我有两个mysqli查询一个接一个,我只能执行第一个


Why when I have two mysqli queries one after another I can execute only the first one?

我写了以下php代码:

if ($insert_client_stmt = $mysqli->prepare("INSERT INTO client (username, email, password) VALUES (?, ?, ?)")) {
    $insert_client_stmt->bind_param('ssss', $username, $email, $password);
    // Execute the prepared query.
    if (! $insert_client_stmt->execute()) {
        header('Location: ../error.php?err=Registration failure: INSERT');
    }
}
$client_id = $mysqli->insert_id;


if ($insert_client_details_stmt = $mysqli->prepare("INSERT INTO client_addr (addr_id, client_id, client_name, contact_name) VALUES (?, ?, ?, ?)")) {
$insert_client_details_stmt->bind_param('ssss', $client_id, $_POST['company'], $_POST['contact']);
// Execute the prepared query.
if (! $insert_client_details_stmt->execute()) {
    header('Location: ../error.php?err=Registration failure: INSERT');
}
}
header('Location: ./register_success.php');

和经过该代码后,我的浏览器将我重定向到页面register_success.php,但在我的数据库中,我只有新客户端,client_addr中的条目缺失。是什么导致的呢?我需要重新设置我自己吗?谢谢!

你的代码有两个问题。

首先,你以最糟糕的方式处理错误。因此,使您无法获得有用的错误消息,这可能会帮助您。为了在mysqli中正确处理错误,你必须摆脱所有这些无用的if,并告诉mysqli在发生错误时抛出异常。

第二个错误本身很简单:您将三个变量传递给第二个查询,而在INSERT查询中有四个字段。您必须从查询

中取出addr_id和相应的占位符

所以,代码应该是。

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $mysqli->prepare("INSERT INTO client (username, email, password) VALUES (?,?,?)");
$stmt->bind_param('sss', $username, $email, $password);
$stmt->execute();
$client_id = $mysqli->insert_id;
$stmt = $mysqli->prepare("INSERT INTO client_addr (client_id, client_name, contact_name) VALUES (?,?,?)");
$stmt->bind_param('sss', $client_id, $_POST['company'], $_POST['contact']);
$stmt->execute();
header('Location: ./register_success.php');