Check to see if an email is already in the database using prepared statements(使用准备好的语句检查电子邮件是否已经在数据库中)
问题描述
我正在尝试将我的代码更改为来自 mysql 的 msqli 准备语句.我不确定如何调整我目前可以检查数据库中是否已有电子邮件的代码.以下是我目前正在使用的有效代码.如何将其更改为准备好的语句并获得相同的结果?
I am trying to change my code to msqli prepared statements from mysql. I am not sure how to adapt my code that currently works to check if there is an email already in the database. Below is the code I am currently using that works. How do I change this into a prepared statement and get the same result?
//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 {
// ....
}
此链接也可能对您有所帮助:
This link may help you as well:
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
这篇关于使用准备好的语句检查电子邮件是否已经在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用准备好的语句检查电子邮件是否已经在数据
基础教程推荐
- 在多维数组中查找最大值 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01