我一直在用HTML编写PHP代码片段,它迭代另一个数组中的数组(来自mysql的数据)。但是当我运行代码时,它会给出以下两个错误。
未定义的变量 ......中的数组到字符串转换...... 以下是我的代码。
$sql = "SELECT * FROM person";
$result = mysqli_query($conn, $sql);
$resultDataSet = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
array_push($resultDataSet, $row);
}
if ($type == "HTML") {
$htmlSerialize = "
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<?php foreach($resultDataSet as $value): ?>
<tr>
<th><?php=?".$value['Name']." ?></th>
<th><?php=?".$value['Age']." ?></th>
<th><?php=?".$value['City']." ?></th>
</tr>
<?php endforeach; ?>
</table>";
echo $htmlSerialize;
}
以下是错误。
我犯的错误是什么?我该如何解决这个问题?
被修改
以下是$ resultDataSet
的var转储array (size=2)
0 =>
array (size=8)
0 => string '1' (length=1)
'ID' => string '1' (length=1)
1 => string 'Akila' (length=5)
'Name' => string 'Akila' (length=5)
2 => string '22' (length=2)
'Age' => string '22' (length=2)
3 => string 'Mount Lavinia' (length=13)
'City' => string 'Mount Lavinia' (length=13)
1 =>
array (size=8)
0 => string '2' (length=1)
'ID' => string '2' (length=1)
1 => string 'Randil' (length=6)
'Name' => string 'Randil' (length=6)
2 => string '23' (length=2)
'Age' => string '23' (length=2)
3 => string 'Colombo' (length=7)
'City' => string 'Colombo' (length=7)
答案 0 :(得分:3)
错误报告value
未定义。 PHP不会解析也不会编译由引号括起来的代码 - 字符串。尝试从HTML输出中分割循环。
if ($type == "HTML") {
// Start by opening the table and header
$htmlSerialize = '
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>';
// loop over the results and append each row to $htmlSerialize
foreach($resultDataSet as $value):
$htmlSerialize .= '
<tr>
<th>'. $value['Name'] .'</th>
<th>'. $value['Age'] .'</th>
<th>'. $value['City'] .'</th>
</tr>';
endforeach;
// close the table
$htmlSerialize .= '</table>';
// flush results
echo $htmlSerialize;
}