Jay
Jay

Reputation: 11179

question about mysqli prepared statements

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.

Upvotes: 0

Views: 1394

Answers (2)

Jon
Jon

Reputation: 437336

bind_result makes 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:

$query = "SELECT Name, CountryCode, District FROM myCity";

You want to execute the query and do something with the results, let's say print them:

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_row()) {
        printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
    }
}

The "problem" with the above code is that $row[0] is not very descriptive. An alternative way is to use bind_result, which goes like this:

$query = "SELECT Name, CountryCode, District FROM myCity";

if ($stmt = $mysqli->prepare($query)) {
    $stmt->bind_result($name, $countryCode, $district);

    while ($stmt->fetch()) {
        printf("%s (%s,%s)\n", $name, $countryCode, $district);
    }
}

As you see, when using bind_result each time you call fetch the variables $name, $countryCode, $district are 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).

Upvotes: 2

Dimitry
Dimitry

Reputation: 6603

bind_result assigns the variable to which data will be written. And you can keep the connection open. Just make sure you call $stmt->fetch() after $stmt->bind_result($district);

Check out Example #1 here: http://www.php.net/manual/en/mysqli-stmt.bind-result.php

Upvotes: 0

Related Questions