当只返回一行时,PHP mysqli无法输出表

时间:2015-01-02 05:13:57

标签: php mysqli

尝试生成通用表,而无需指定列名,因为在select语句中注意了名称。当select语句返回零行或多行时,下面的代码工作正常,但只返回正好返回1行时才打印表头。

感谢您的建议。

这是我的代码:

$qry1 = "SELECT distinct subject.code as 'subject', subject.name as 'course', event.event_desc as 'description' FROM applicant, event, subject, part where applicant.applicant_id = $m_id and applicant.event_id = event.id and event.subject_id=subject.id and part.id = subject.owner_id and part.id = $p_id order by event.active DESC, event.from_month DESC ";

$result = mysqli_query($bd, $qry1);

$finfo = mysqli_fetch_fields($result);

$outp = '<div><table><tr>';
$i = 0;
foreach ($finfo as $val) {
   $outp .= '<th>';
   $outp .= $val->name;
   $outp .= '</th>';
   $i++;
}
$outp .= '</tr>';
if (mysqli_num_rows($result) > 0) {
    $outp .= '<tr>';
    while ($rs = mysqli_fetch_array($result)) {
        for ($j = 0; $j < $i; $j++) {
            $outp .= '<td>';
            $outp .= $rs[$j];
            $outp .= '</td>';
        }
        $outp .= '</tr>';
    }
} else {
   $outp .= '<tr><td colspan =';
   $outp .= $i + 1;
   $outp .= '>';
   $outp .= "no course found";
   $outp .= '</td></tr>';
}
$outp .= '</table></div>';

mysqli_close($bd);

echo ($outp);

1 个答案:

答案 0 :(得分:0)

我建议简化代码如下(未解析 - 请检查语法):

    $result = mysqli_query($bd, $qry1);

    $outp = '<div><table><tr>';
    for($i = 0; $i < mysql_num_fields($result); $i++) {
        $finfo = mysql_fetch_field($result, $i);
        $outp .= '<th>{$finfo->name}</th>';
    }

    if (mysqli_num_rows($result) > 0) {
    $outp .= '<tr>';
        while($rs = mysql_fetch_row($result)) {

            foreach($rs as $col) {
                $outp .= '<td>{$col}</td>';
            }

        }
        $outp .= '</tr>';
    }
    else {
       $outp .= '<tr><td colspan =';
       $outp .= $i + 1;
       $outp .= '>';
       $outp .= "no course found";
       $outp .= '</td></tr>';
    }
    $outp .= '</table></div>';

    mysqli_close($bd);

    echo ($outp);