简体   繁体   中英

My MySQL prepared statement won't work

I have a MySQL statement that won't work for me. I've checked several parts of the code but it keeps returning null as the result. 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.

  $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

Also there is absolutely no reason to escape_string when using prepared statements as @GrumpyCrouton said

i would recommend you switch to PDO as it is more straightforward

I agree with @Akintunde that you should NOT use escaping and htmlspecialchars on query parameters. Escaping is redundant when you use query parameters. htmlspecialchars is just when you output content to HTML, not for input to SQL.

You don't necessarily have to use bind_result() for a mysqli query. 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. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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