我希望简化我的应用程序构建查询的方式并循环遍历结果。大多数实际代码都有效,除了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显示第一个字段的值但跳过另外两个字段?
答案 0 :(得分:1)
问题结果是我的数组中的每个字段名之前的空格(上面的示例中没有显示)。
字段数组实际上是
$arr_fields = array('color', ' number', ' size');
删除空格后,值会像往常一样显示出来。感谢Norbert通过额外的测试帮助我指明正确的方向。
答案 1 :(得分:0)
更改此行:
$row_fields.= "<td>$r[$f]</td>";
为:
$row_fields.= "<td>".$r[$f]."</td>";