简体   繁体   English

我的MySQL准备语句无法正常工作

[英]My MySQL prepared statement won't work

I have a MySQL statement that won't work for me. 我有一条MySQL语句对我不起作用。 I've checked several parts of the code but it keeps returning null as the result. 我检查了代码的几部分,但结果一直返回null。 I've also tried replacing the WHERE enc_mail = AND enc_public_id=" to "WHERE 1" to check if it was a problem with the variables, but it is not. I did not get errors either. 我还尝试将WHERE enc_mail = AND enc_public_id=" to "WHERE 1"替换WHERE enc_mail = AND enc_public_id=" to "WHERE 1"以检查变量是否存在问题,但事实并非如此,我也没有收到错误。

  $connect_db = mysqli_connect("myhost","my username","my password","my db");

    $mail_id = crypto(mysqli_real_escape_string($connect_db,htmlspecialchars($_GET['em'])),'e');
    $public_id = mysqli_real_escape_string($connect_db,htmlspecialchars($_GET['public']));
    $active_true = true;
    $check = $connect_db->prepare("SELECT active FROM enc_data WHERE enc_mail=? AND enc_pub_id=?");
    $check->bind_param("ss", $mail_id, $public_id);
    $active = $check->execute();

        if($active[0]=="" ){
        //It goes here once the code is run
    }

You need to apply bind_result and then fetch 您需要应用bind_result然后fetch

Also there is absolutely no reason to escape_string when using prepared statements as @GrumpyCrouton said 也有是绝对没有理由escape_string使用预处理语句作为@GrumpyCrouton说,当

i would recommend you switch to PDO as it is more straightforward 我建议您切换到PDO,因为它更直接

I agree with @Akintunde that you should NOT use escaping and htmlspecialchars on query parameters. 我同意@Akintunde的建议,不要在查询参数上使用转义和htmlspecialchars。 Escaping is redundant when you use query parameters. 使用查询参数时,转义是多余的。 htmlspecialchars is just when you output content to HTML, not for input to SQL. htmlspecialchars只是当您将内容输出到HTML时,而不是将其输入到SQL时。

You don't necessarily have to use bind_result() for a mysqli query. 您不一定必须对MySQLi查询使用bind_result()。 You can get a result object from the prepared statement, and then use fetch methods on the result object to get successive rows. 您可以从准备好的语句中获取结果对象,然后对结果对象使用访存方法来获取连续的行。

Here's how I would write your code: 这是我编写您的代码的方式:

// makes mysqli throw exceptions if errors occur
mysqli_report(MYSQLI_REPORT_STRICT);

$connect_db = new mysqli("myhost", "my username", "my password", "my db");

$mail_id = $_GET['em'];
$public_id = $_GET['public'];
$active_true = true;
$sql = "SELECT active FROM enc_data WHERE enc_mail=? AND enc_pub_id=?";
$stmt = $connect_db->prepare($sql);
$stmt->bind_param("ss", $mail_id, $public_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    if($row["active"]=="" ){
        //It goes here once the code is run
    }
}

But in fact I would prefer to use PDO instead of mysqli, so I guess that's not really how I would write the OP's code. 但是实际上,我更愿意使用PDO代替mysqli,因此我想那并不是我编写OP代码的真正方式。 :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM