【问题标题】:Check to see if an email is already in the database using prepared statements使用准备好的语句检查电子邮件是否已经在数据库中
【发布时间】:2012-02-22 23:49:28
【问题描述】:

我正在尝试将我的代码更改为来自 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?
}

【问题讨论】:

  • 欢迎您。我已尽我所能重新格式化您的帖子。请务必阅读常见问题解答以习惯标记。缺少一些您可能想要发布的代码。

标签: php mysqli prepared-statement


【解决方案1】:

应该是这样的:

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

【讨论】:

  • 谢谢,但我收到一个错误:致命错误:在非对象上调用成员函数 bind_param()
  • OK 排序,我添加了(电子邮件)而不是(*)
  • $stmt-&gt;bind_param($email) 应该是$stmt-&gt;bind_param('s', $email)
猜你喜欢
  • 2010-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-15
  • 1970-01-01
  • 2014-05-09
  • 2014-05-10
相关资源
最近更新 更多