I have basic question about mysqli prepared statements. For example, I want to execute a SELECT query, Should I do it like:
<?
$city = "Amersfoort";
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
$stmt->execute();
$stmt->bind_result($district);
$stmt->close();
}
$mysqli->close();
?>
In the above code, is bind_result also required? What exactly it does?
Also, do I need need to close mysqli connection after each query?
Thanks.
bind_resultmakes it so that when you iterate over the results of the query, the columns from the result set are automatically mapped to local variables.For example, suppose you execute a query that returns a result set with three columns like this:
You want to execute the query and do something with the results, let’s say print them:
The “problem” with the above code is that
$row[0]is not very descriptive. An alternative way is to usebind_result, which goes like this:As you see, when using
bind_resulteach time you callfetchthe variables$name,$countryCode,$districtare automatically populated with the values from the current result row. There are some details that you must ensure, read the documentation for more info.To answer your other question: you do not need to, and indeed you must not close the connection after each query (unless you know very well what you are doing).