I am working on a user registration page. I want to check if the username or email exist before an account is created. I saved the stored query from the prepared statement into the variable "$result" using mysqli_stmt_get_result and tried to fetch the result using mysqli_fetch_array, but I got an error that read;
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, bool given in localhost
The codes below resulted in "result empty". This is the main issue.
$result = mysqli_stmt_get_result($stmt);
if($result) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
if($row['username']==$username && $row['email']==$useremail){
header("Location: ../register.php?error=error&usernametaken&emailexist");
exit();
}
elseif($row['username']==$username){
header("Location: ../register.php?error=error&usernametaken");
exit();
}
elseif($row['email']==$useremail){
header("Location: ../register.php?error=error&emailexist");
exit();
}
}
} else {
echo "result is empty";
}
Below is the full code
$sql = "SELECT username, email FROM users WHERE username = ? OR email = ?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../register.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ss", $username, $useremail);
mysqli_stmt_execute($stmt);
//check if the username exist
mysqli_stmt_store_result($stmt);
$rowCount = mysqli_stmt_num_rows($stmt);
$result = mysqli_stmt_get_result($stmt);
if($rowCount > 0) {
if($result) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
if($row['username']==$username && $row['email']==$useremail){
header("Location: ../register.php?error=error&usernametaken&emailexist");
exit();
}
elseif($row['username']==$username){
header("Location: ../register.php?error=error&usernametaken");
exit();
}
elseif($row['email']==$useremail){
header("Location: ../register.php?error=error&emailexist");
exit();
}
}
} else {
echo "result is empty";
}
} else {
$sql = "INSERT INTO users (username, email, name, password) VALUES (?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../register.php?error=sqlerror");
exit();
} else {
$hashedPass = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ssss", $username, $useremail, $first_name, $hashedPass);
mysqli_stmt_execute($stmt);
header("Location: ../register.php?success®istered");
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
I am running it on a local server though. I humbly await your input.