我的MySQL预编译语句不起作用

时间:2017-10-17 20:01:02

标签: php mysql mysqli prepared-statement

我有一个不适合我的MySQL声明。我检查了代码的几个部分,但结果却一直返回null。我也试过替换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
    }

2 个答案:

答案 0 :(得分:1)

您需要应用bind_result然后fetch

使用预准备语句时,escape_string绝对没有理由,因为@GrumpyCrouton说

我建议您切换到PDO,因为它更直接

答案 1 :(得分:1)

我同意@Akintunde你不应该在查询参数上使用转义和htmlspecialchars。使用查询参数时,转义是多余的。 htmlspecialchars就是当你输出内容到HTML时,而不是输入到SQL。

您不一定要使用bind_result()来进行mysqli查询。您可以从预准备语句中获取结果对象,然后在结果对象上使用fetch方法来获取连续的行。

以下是我编写代码的方法:

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

但实际上我更喜欢使用PDO而不是mysqli,所以我想这不是真的我将如何写OP的代码。 : - )

相关问题