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

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

问题描述:

我正在尝试将我的代码从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?
}

应该是这样的:

// 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->store_result();

// get the count
$numRows = $stmt->num_rows();

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