我写了以下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?谢谢!
答案 0 :(得分:1)
您的代码中存在两个问题。
首先,你是以最坏的方式处理错误。因此剥夺了自己无法获得有用的错误消息,这可能对您有所帮助。对于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');