[英]php check if email exists in mysql database
For some reason it always returns 0 even when there is an identical email in the database.出于某种原因,即使数据库中有相同的 email,它也总是返回 0。 Is there something wrong with my syntax?
我的语法有问题吗? The code worked when I did it without a prepare/execute statement.
当我在没有准备/执行语句的情况下执行此代码时,该代码有效。 Is it necessary here for security reasons?
出于安全原因,这里有必要吗?
$email= $conn->real_escape_string($_POST['email']);
function emailExists($conn, $email) {
$stmt = $conn->prepare("SELECT 1 FROM accountInfo WHERE email=(?)");
$stmt->bind_param($email);
$stmt->execute();
return $stmt->num_rows;
}
echo emailExists($conn, $email);
Don't use real_escape_string()
.不要使用
real_escape_string()
。 When you use parameter binding there is no need to escape anything.当您使用参数绑定时,无需转义任何内容。
Parameter binding in mysqli is rather difficult as you have to remember the strange syntax of bind_param()
. mysqli 中的参数绑定相当困难,因为您必须记住
bind_param()
的奇怪语法。 At least 2 arguments are needed, the first is a string of characters representing the types of values.至少需要2个arguments,第一个是代表值类型的字符串。 You don't have that.
你没有那个。
SQL doesn't need brackets around parameters. SQL 参数不需要括号。 You can just do
email=?
你可以只做
email=?
. .
When you want to check the existence of something using SQL, then you don't need to use $stmt->num_rows
.当您想使用 SQL 检查某物是否存在时,您不需要使用
$stmt->num_rows
。 You can use COUNT(1)
in SQL, which should be simpler.可以在 SQL 中使用
COUNT(1)
,应该更简单。 In fact, forget about the existence of this function/property as it leads to many mistakes like yours and is generally not useful.事实上,忘记这个函数/属性的存在,因为它会导致像你这样的许多错误并且通常没有用。
When we fix all the small problems the code should look something like this:当我们修复所有小问题时,代码应该如下所示:
$email = $_POST['email'];
function emailExists(mysqli $conn, string $email):bool {
$stmt = $conn->prepare("SELECT COUNT(1) FROM accountInfo WHERE email=? LIMIT 1");
$stmt->bind_param('s', $email);
$stmt->execute();
return (bool) $stmt->get_result()->fetch_row[0];
}
echo emailExists($conn, $email);
You just need to add $stmt->store_result();
您只需要添加
$stmt->store_result();
function emailExists($conn, $email) {
$stmt = $conn->prepare("SELECT 1 FROM accountInfo WHERE email=? LIMIT 1");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.