$ query-> get_result()是获得结果的正确方法吗?

时间:2014-11-29 06:57:26

标签: php mysqli prepared-statement

我目前有以下代码;

$sql = 'SELECT * FROM customers';
$query = $con->prepare( $sql );
$query->execute();
$rr = $query->get_result();


while ($s = $rr->fetch_assoc()) {
    echo '<tr>';
    echo '<td>' . $s['name'] . '</td>';
    echo '<td>' . $s['email'] . '</td>';
    echo '<td>' . $s['mobile'] . '</td>';
    echo '</tr>';
}

这是使用mysqli从数据库获取结果的正确方法吗?

3 个答案:

答案 0 :(得分:1)

这是从预准备语句中获取结果的完全可接受的方式,但只有在安装了本机mysqli扩展时才会有效(如果你有本机PHP安装,那么它应该存在)。你也可以使用$query->bind_result()并直接填充变量,就像这样;

$sql = 'SELECT name,email,mobile FROM customers';
$query = $con->prepare( $sql );
$query->execute();
$query->bind_result($name, $email, $mobile);

while ($query->fetch()) {
    echo '<tr>';
    echo '<td>' . $name . '</td>';
    echo '<td>' . $email . '</td>';
    echo '<td>' . $mobile . '</td>';
    echo '</tr>';
}

请注意,每次调用$query->fetch()时,变量都会被填充(按照从数据库中检索的顺序,因此我在示例中明确命名了列的原因)和下一行的数据,所以你需要while循环遍历所有数据。

希望这有帮助。

答案 1 :(得分:1)

<?php

//First make a connection to the database server:
$mysql = new mysqli("host_or_ip", "username", "password", "database");

//Then check your new connection
if($mysql->connect_errno){
    die("DB connection failed: ", $mysql->connect_error);
}

//Run a select query and check there are no errors
$result = $mysql->query("SELECT book_name FROM bookshelf LIMIT 30");
if(!result){
    die("Error running query: ".$result->error);
}

//Output the results
echo("".
    "<table>".
        "<thead>".
            "<tr>".
                "<th>Book Name</th>".
                "<th>Author</th>".
                "<th>Publisher</th>".
            "</tr>".
        "</thead>".
        "<tbody>");

while($row = $result->fetch_assoc()){
    echo '<tr>';
    echo '<td>'.$row['book_name'].'</td>';
    echo '<td>'.$row['author'].'</td>';
    echo '<td>'.$row['publisher'].'</td>';
    echo '</tr>';
}

echo("</tbody></table>");

答案 2 :(得分:-1)

我不知道您是否与db建立了连接。 请检查此示例:

<?php
    $mysqli = new mysqli($dbHost, $dbUsername, $dbPassword, $dbDatabase);
    $stmt = $mysqli->prepare('select * from foobar');
    $stmt->execute();
    $stmt->store_result();
    $meta = $stmt->result_metadata();

    while ($column = $meta->fetch_field()) {
       $bindVarsArray[] = &$results[$column->name];
    }       
    call_user_func_array(array($stmt, 'bind_result'), $bindVarsArray);

    $stmt->fetch();

    echo var_dump($results);
    // outputs:
    //
    // array(3) {
    //  ["id"]=>
    //  &int(1)
    //  ["foo"]=>
    //  &string(11) "This is Foo"
    //  ["bar"]=>
    //  &string(11) "This is Bar"
    // }
    ?>