PHP 循环 mysqli 结果而不知道字段名称[重复]

问题描述 投票:0回答:1

我正在尝试输出一个包含字段名称的表格,然后全部按行排列。字段名称有效,但数据不输出。

    $result = mysqli_query($mysqli, "SELECT * FROM tasks");
    $rows = mysqli_fetch_all($result, MYSQLI_ASSOC);

    $fields = mysqli_fetch_fields($result); 

    foreach ($fields as $val) {   //loop thru and output field names for header row
        echo "\t<td class='centerstuff'>$val->name</td>\n"; 
    }
    echo "\n</tr>\n";

    while($row = mysqli_fetch_assoc($result)) { 
      echo "<tr>";
      foreach ($row as $key=>$value)
          echo "\t<td class='small'>" .$value ."</td>\n";  //foreach field make a cell, echo out the value, close the cell
          echo "</tr>\n"; //close the row 
  echo "\n";
}

在我看来,PHP 不太可能强迫您对字段名称进行硬编码。尽管手册中的每个示例都是如此(叹气)。

我知道 mysqli_fetch_assoc 是一个数组。我不想获取行的长度,启动一个计数器,然后从 [1] 输出。是的。 [0] 似乎总是保存字符串“Array”。

php loops foreach mysqli
1个回答
1
投票

mysqli_fetch_all 返回一个关联数组。这意味着键是列名称,因此您可以执行类似的操作。

$result = mysqli_query($mysqli, "SELECT * FROM tasks");

//this returns all rows from the database into an associative array. There is no need to fetch each row again
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);

//if this is false, no rows were returned by the query
if(!empty($rows)) {

   //get an array of returned columns
   $columns = array_keys($rows[0]);

   //start table element, table head, and first row
   echo "<table><thead><tr>";

   //loop over columns and add them as <th> elements
   foreach($columns as $column) {
      echo "<th>{$column}</th>";
   }

   //end first row, and table head, begin table body
   echo "</tr></thead><tbody>";

   //loop over all returned rows
   foreach($rows as $row) {

      //for each row, create a <tr> element
      echo "<tr>";

      //loop over returned columns again. This should ensure the values are in the same order as the headers
      foreach($columns as $column) {

         //fetch the specific column value based on $column
         $column_value = $row[$column];

         //create a <td> element for each column value
         echo "<td>{$column_value}</td>";
      }

      //end <tr> once all columns are printed
      echo "</tr>";
   }

   //end table body and table element
   echo "</tbody></table>";
}
© www.soinside.com 2019 - 2024. All rights reserved.