所以我正在执行MYSQLI事务(仅供参考我是PHP和MYSQL的新手)。我有3个关系表,一个用户,user_auth,user_info。 users是存储主键的位置,自动递增整数设置为最多11个字符。这是我的查询代码(顺便提一下这是注册表格)
<?php
if (isset($_POST['submit'])) {
// Process the form
// validations
$required_fields = array("firstname", "lastname", "email", "password", "passwordConfirm");
validate_presences($required_fields);
if (empty($errors)) {
mysqli_autocommit($connection, false);
// Attempt Login
$flag = true;
$firstName = $_POST["firstname"];
$lastName = $_POST["lastname"];
$email = $_POST["email"];
$password = password_encrypt($_POST["password"]);
if ($_POST["password"] != $_POST["passwordConfirm"]) {
$_SESSION["message"] = "Password do not match.";
return false;
}
$userList = find_admin_by_username($email);
if ($userList) {
$_SESSION["message"] = "This email is already in use please use another email.";
return false;
} else {
$query1 = "INSERT INTO users (";
$query1 .= " email";
$query1 .= ") VALUES (";
$query1 .= " '{$email}'";
$query1 .= ")";
$result = mysqli_query($connection, $query1);
if (!$result) {
$flag = false;
}
$newUser = find_admin_by_username($email);
$newUserID = $newUser["id"];
$query2 = "INSERT INTO user_auth (";
$query2 .= " user_id, hashed_password";
$query2 .= ") VALUES (";
$query2 .= " '{$newUserID}', '{$password}'";
$query2 .= ")";
$result = mysqli_query($connection, $query2);
if (!$result) {
$flag = false;
}
$query3 = "INSERT INTO user_info (";
$query3 .= " user_id, first_name, last_name";
$query3 .= ") VALUES (";
$query3 .= " '{$newUserID}', '{$firstName}', '{$lastName}'";
$query3 .= ")";
$result = mysqli_query($connection, $query3);
if (!$result) {
$flag = false;
}
if ($flag) {
mysqli_commit($connection);
$_SESSION["message"] = "User creation successful.";
redirect_to('signup.php');
} else {
mysqli_rollback($dbConnection);
$_SESSION["message"] = "There was an error in creating this user. Please try again. If the issue persists contact us through our contact form";
redirect_to('signup.php');
}
}
}
}// end: if (isset($_POST['submit']))
?>
在语句中你可以看到我在第一次插入后分配一个变量来获取注册用户的新id
$newUser = find_admin_by_username($email);
$newUserID = $newUser["id"];
找到用户名的函数是:
function find_admin_by_username($username) {
global $connection;
$safe_username = mysqli_real_escape_string($connection, $username);
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE email = '{$safe_username}' ";
$query .= "LIMIT 1";
$admin_set = mysqli_query($connection, $query);
confirm_query($admin_set);
if($admin = mysqli_fetch_assoc($admin_set)) {
return $admin;
} else {
return null;
}
}
因此在insert语句中,您可以看到我将$ newUser作为字符串插入user_auth和user_info表。出于某种原因,如果我把它放在没有''并且因为它是一个整数我的查询失败并且错误输出。是否有一个原因?我知道它会自动将其转换为mysql字段中所需的内容,但我更愿意遵循最佳实践(而且我也想了解为什么教育会发生这种情况)。
我感谢您的任何帮助,我已经三次检查数据库,这些字段实际上是整数,我有一个我工作的主要数据库人员检查数据库并确认它们被设置为整数