Mysqli查询无法获取结果

时间:2017-05-15 22:27:33

标签: php mysqli

我有这个代码,我想打印一个包含内容的表。它打印表但列是空的...我错过了什么?我看不出错误..

function show_autovetture($data){

    $con = $data;               //PASSO CONNESSIONE
    $rows = array();            // PREPARO ARRAY

    $stmt = mysqli_stmt_init($con); // INIZIALIZZO LA CONNESSIONE

    mysqli_stmt_prepare($stmt,'SELECT
                        autovetture.id,
                        autovetture.name
                        FROM autovetture
                        ORDER BY id DESC');
                        or die(mysqli_error($con)); // QUERY INSERIMENTO DATI

    mysqli_stmt_execute($stmt);                    // ESEGUO LA QUERY

    mysqli_stmt_bind_result($stmt,$rows['id'],$rows['name']);

    $html = "";
    $html .= "<div class='container'>";
    $html .= "<div class='div_box_5'>";
    $html .= "<div class='row'>";
    $html .= "<div class='panel panel-default'>";
    $html .= "<div class='panel-heading'>";
    $html .= "<h4>";
    $html .= "Elenco Ditte Autovetture"; 
    $html .= "</h4>";
    $html .= "</div> <!-- end panel-heading -->";
    $html .= "<table class='table table-fixed'>";
    $html .= "<thead>";
    $html .= "<tr>";
    $html .= "<th class='col-xs-2'>#</th><th class='col-xs-8'>Nome</th><th class='col-xs-2'>Modifica</th>";
    $html .= "</tr>";
    $html .= "</thead>";
    $html .= "<tbody>";
    while($rows=mysqli_stmt_fetch($stmt)){
            $html .= "<tr>";
            $html .= "<td class='col-xs-2'>$rows[id]</td><td class='col-xs-8'>$rows[name]</td><td class='col-xs-2'><a href='edit_autovet.php?id=$rows[id]'><span class='glyphicon glyphicon-pencil'></span></a></td>";
            $html .= "</tr>"; 
    }
    $html .= "</tbody>";
    $html .= "</table>";
    $html .= "</div> <!-- end panel panel-default -->";
    $html .= "</div> <!-- end row -->";
    $html .= "</div> <!-- end div_box_5 -->";
    $html .= "</div> <!-- end container -->";


    mysqli_stmt_close($stmt);                                       // CHIUDO LO STATEMENT
    mysqli_close($con);                                             // CHIUDO CONNESSIONE   

    return $html;

}

错误在哪里?

1 个答案:

答案 0 :(得分:2)

当你用mysqli_stmt_bind_result($stmt,$rows['id'],$rows['name']);绑定它们时,结果已经绑定了,即使你循环它们也会在那些变量中 - 在获取时循环的每次迭代都会更新变量的内容 - 所以你只想以mysqli_stmt_fetch()作为参数循环,而不是像这样分配变量

while (mysqli_stmt_fetch($stmt)) {

而不是

while($rows=mysqli_stmt_fetch($stmt)){

使用语句获取数据与使用mysqli_fetch_*()方法获取数据略有不同。

您当前正在覆盖$rows变量,使其成为布尔值(true / false),或者当您像现在一样运行它时为null。有关返回值,请参阅mysqli_stmt_fetch()手册。