我想簡化應用程序如何構建查詢並循環遍歷結果。大部分實際代碼都可以工作,除了PHP不顯示從我的查詢中獲取的所有結果。創建字段數組然後循環遍歷PHP中的集合
前言:示例代碼提前,請勿在生產中使用。
首先我構建查詢。
$arr_fields = array('color', 'number', 'size');
$select_fields = implode(', ', $arr_fields);
$q = "SELECT $select_fields FROM supplychain";
現在我執行查詢,然後遍歷結果集。
專業提示:請勿將此代碼用於任何重要內容 - 僅用於演示目的。
echo "<table>";
$res = doQuery($q);
// create report body
foreach($res as $r)
{
// set values from array of field names
$row_fields = '';
foreach ($arr_fields as $f)
{
// set current $arr_field value inside a table cell...
$row_fields.= "<td>$r[$f]</td>";
}
// display the row
echo "<tr>$row_fields</tr>";
}
echo "</table>";
從$arr_fields
(color
)第一數據庫值被輸出作爲預期,其餘都沒有。
在MySQL控制檯發出的組裝查詢顯示的值爲color, number and size
。腳本沒有生成任何SQL錯誤。
爲什麼PHP顯示第一個字段的值但跳過了另外兩個?
應該工作,什麼是'print_r($ res);'? – AbraCadaver
'陣列 ( [顏色] =>紅色 [數字] => 33145551 [尺寸] =>大 )' –