简体   繁体   中英

binding parameters in MySQl and PHP

I am trying to learn how to use prepared statements in my PHP, to get data out from MySQL database. At the moment I am not getting anything printed out.

I need to have a while loop there is going through my rows in the database. Is that correct?

Am I on the correct way here, or what am I missing? I made some comments in the code, to describe what I am doing.

    <?php

    $stmt = $mysqli->prepare("SELECT * FROM fantasies WHERE headline = ? AND description = ? AND place = ? ORDER BY reg_date DESC LIMIT 3");

                // Execute prepared statement 
                if ($stmt->execute()) {
                    $success = true;
                }

                // Make variables ready
                $head = null;
                $desc = null;
                $plac = null;

                // Bind result to variables
                $stmt->bind_result($head, $desc, $plac);

                while ($stmt->fetch()) {

                    // What should go here?
                    echo "Headline: ".$head."Description: ".$desc."Place: ".$place;
                }
                // Close statement
                $stmt->close();

                // Close connection
                $mysqli->close();   

if($success) {
    echo "Selected Succesfull";
} else {
    echo "Failed: " .  $stmt->error;
  }
}
?>

That code when executed it should give you an error :

Invalid parameter number: no parameters were bound

You need to bind your parameters as you are using placeholders

$stmt->bind_param("sss", $headline, $description, $place); //missing from your code

where "sss" is the dataType in this case a string and $headline, $description, $place are your variables that you replacing with placeholders

Your code should be

<?php

$stmt = $mysqli->prepare("SELECT * FROM fantasies WHERE headline = ? AND description = ? AND place = ? ORDER BY reg_date DESC LIMIT 3");

//bind parameters
$stmt->bind_param("sss", $headline, $description, $place);

if ($stmt->execute()) {
    $stmt->bind_result($head, $desc, $plac);

    while ($stmt->fetch()) {

        echo "Headline: " . $head . "desc: " . $desc . "Place: " . $plac;
    }
    $stmt->close();
} else {

    echo "error" . $mysqli->error;
}

$mysqli->close();

?>

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