我有这部分代码:
........
$topic_name = "";
........
function getAllTopics() {
global $conn;
$sql = "SELECT * FROM topics";
$result = mysqli_query($conn, $sql);
$topics = mysqli_fetch_assoc($result);
return $topics;
}
我遇到类似
的错误“ PHP警告:行中的字符串偏移量'name'非法...”
前端的代码部分是:
<tbody>
<?php foreach ($topics as $key => $topic): ?>
<tr class="odd gradeX">
<th><?php echo $key + 1; ?></th>
<th><?php echo $topic['name']; ?></th>
</tr>
</tbody>
我在做什么错?
答案 0 :(得分:1)
我可以看到您现有代码和逻辑的许多问题。
<? endforeach; ?>
的循环foreach
getAllTopics()
之前不调用$topics
foreach
循环中的变量。mysqli_fetch_assoc()
提取 a 结果行作为
关联数组,而不是表中的所有行。我想您可以略微修改现有代码,并以这种方式进行[未经测试,但希望您明白我的意思]
function getAllTopics() {
global $conn;
$sql = "SELECT * FROM topics";
$result = mysqli_query($conn, $sql);
$result = mysqli_fetch_assoc($result);
while ($row = mysql_fetch_assoc($result)) {
$topics[] = $row; // this will get every single row from table result and push it to $topics array.
}
return $topics;
}
<tbody>
<?php
$topics = getAllTopics(); // this will get all the topics
foreach ($topics as $key => $topic): ?>
<tr class="odd gradeX">
<th><?php echo $key + 1; ?></th>
<th><?php echo $topic['name']; ?></th>
</tr>
<? endforeach; ?> // this is the missing endforeach; syntax
</tbody>