PHP准备语句 - MySQL检查用户是否存在

时间:2015-03-02 05:41:43

标签: php

我不知道为什么我的代码似乎无法正常工作。我想检查数据库中是否存在电子邮件,如果它不存在则继续注册。这是代码:

if (empty($errors)) {  //Using Prepared Statements
// Connect to the database:
$dbc = mysqli_connect ('localhost','root', 'pass', 'book_store');  
$q = "SELECT user_id FROM users WHERE email=?";
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 'i', $email);
    mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$num_rows = mysqli_num_rows($result);


if ($num_rows == 0) {  //Check if email exists
$q = 'INSERT INTO users(first_name, last_name, state, email) VALUES (?, ?, ?,     ?)';
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt,'ssss', $fn, $ln,$state, $email);
mysqli_stmt_execute($stmt);

// Closee statement:
mysqli_stmt_close($stmt);

// Close the connection:
    mysqli_close($dbc);

} else {
echo '<h1>email exists</h1>';
} 
}
else {
 echo '<p>The Errors Occurred:<br />';
 foreach ($errors as $msg) {
     echo " - $msg<br />\n";
 }
 echo '</p><p>Please Try Again.</p>';
}
}

1 个答案:

答案 0 :(得分:2)

您已经提供了i,它表示int类型的变量。尝试将其替换为s,如下所示。 $q = "SELECT user_id FROM users WHERE email=?"; $stmt = mysqli_prepare($dbc, $q); mysqli_stmt_bind_param($stmt, 's', $email);

相关问题