PHP/MYSQLI - 如何检查此查询是否可行,如果是,则显示错误(请参阅示例)


PHP/MYSQLI - How to check if this query is possible, if so show error (see example)

我正在学习一些myqli,想做一个简单的检查。

基本上,用户将输入他们的电子邮件地址然后提交表单,如果电子邮件地址已经包含在某个mysql表中,则脚本必须停止并显示错误。

这是我的例子:

$userEmail = sanitize($_POST['specials']);          
// Check to see if email already exists, if not proceed
if ($stmt = $link->prepare("SELECT email FROM specials WHERE email=$userEmail"))
{
    $specialsErrorFocus = 'autofocus="autofocus"';
    $specialsInfo = 'This email address: $userEmail, is already in our database.';
    include "$docRoot/html/shop/home.html.php";
    exit();
}

此代码没有按照我的预期执行,如描述的那样。

有人可以解释一下我在这方面出了什么问题,或者可能为此任务提供更好的解决方案。

提前感谢!

您需要先执行查询,因为仅仅准备语句是不够的。请参阅文档,因为它是一个多阶段过程。

首先,准备语句:

$stmt = $link->prepare("SELECT `email` FROM `specials` WHERE `email` = ?")
if (!$stmt) {
   echo $link->errno . " : " . $link->error;
}

接下来,绑定参数:

if (!$stmt->bind_param("s", $userEmail)) {
    echo $stmt->errno . " : " . $stmt->error;
}

最后,执行查询:

if (!$stmt->execute()) {
    echo $stmt->errno . " : " . $stmt->error;
}

获取结果:

$stmt->store_result();
if ($stmt->num_rows) {
   # Email exists
}

准备 不执行该语句。您可以使用 mysql::query 来执行语句。

您的示例将变为:

$result = $link->query("SELECT email FROM specials WHERE email=$userEmail");    
if ( $result ) {
    if ( $result->num_rows > 0 ) {
        $specialsErrorFocus = 'autofocus="autofocus"';
        $specialsInfo = 'This email address: $userEmail, is already in our database.';
        include "$docRoot/html/shop/home.html.php";
        exit();
    }
}