Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

php - Check to see if an email is already in the database using prepared statements

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?
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Should be something like this:

// 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...