Having this code:
$sql = "SELECT * FROM users WHERE user_login=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
die(mysqli_error($conn));
} else {
mysqli_stmt_bind_param($stmt, 's', $login);
mysqli_stmt_execute($stmt);
mysqli_store_result($conn);
$resultCheck = mysqli_stmt_num_rows($stmt);
//err == login name is already taken
if ($resultCheck > 0) {
die("login is taken");
} else {
$sql = "INSERT INTO users(user_login, user_email, user_pwd) VALUES (?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
die(mysqli_error($conn));
} else {
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, 'sss', $login, $email, $hashedPwd);
mysqli_stmt_execute($stmt);
}
// insert_usertodb($conn, $login, $email, $pwd);
}
}
works fine (`e.g. the part where is user inserted does not gives any mysqli error), however, if I tried to use a function, where the user is inserted:
function insert_usertodb($conn, $user_login, $user_email, $user_pwd)
{
$sql = "INSERT INTO users(user_login, user_email, user_pwd) VALUES (?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) { // <-- this is where the error happens
// err_signup('sqlierror', '', '');
die('sqlierror: ' . mysqli_error($conn));
} else {
//hash password
$hashedPwd = password_hash($user_pwd, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, 'sss', $user_login, $user_email, $hashedPwd);
mysqli_stmt_execute($stmt);
// header("Location: ../signup.php?signup=success");
}
}
And use it instead of the part, where the user is inserted (after else
branch -> the function is commented at the end), the mysqli generates error:
Commands out of sync; you can't run this command now
Is there any reason, why the function with identical code (like literally copied the part (where is the insertion) and just change the variables name to be the argument that function) generates the out-of-sync error? and the code without the func doesn't?
My Answer:
resolve this issue by executing the `mysql_free_result()` function to free up the current result set before executing another query. This will ensure that the commands are not out of sync and can be executed sequentially.
Rate this post
3 of 5 based on 5503 votesComments