gpt4 book ai didi

php - 使用准备好的语句检查电子邮件是否已经在数据库中

转载 作者:行者123 更新时间:2023-12-02 05:19:05 24 4
gpt4 key购买 nike

我正在尝试将我的代码更改为来自 mysql 的 msqli 准备语句。我不确定如何调整我目前可以检查数据库中是否已有电子邮件的代码。以下是我目前正在使用的有效代码。如何将其更改为准备好的语句并获得相同的结果?

//if email is equal to an email already in the database, display an error message

if(mysql_num_rows(mysql_query("SELECT * FROM users WHERE email = '".mysql_real_escape_string($_POST['email'])."'")))
{
echo "<p class='red'>Email is already registered with us</p>";
} else {
// missing code?
}

最佳答案

应该是这样的:

// enable error reporting for mysqli
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// create mysqli object
$mysqli = new mysqli(/* fill in your connection info here */);

$email = $_POST['email']; // might want to validate and sanitize this first before passing to database...

// set query
$query = "SELECT COUNT(*) FROM users WHERE email = ?";

// prepare the query, bind the variable and execute
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $email);
$stmt->execute();

// grab the result
$stmt->bind_result($numRows);
$stmt->fetch();

if ($numRows) {
echo "<p class='red'>Email is already registered with us</p>";
} else {
// ....
}
此链接也可能对您有所帮助:
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

关于php - 使用准备好的语句检查电子邮件是否已经在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9405093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com