gpt4 book ai didi

php - 如何解决非法字符串偏移错误并显示以下代码片段中的表格?

转载 作者:行者123 更新时间:2023-11-29 11:29:04 25 4
gpt4 key购买 nike

我正在尝试使用以下 PHP 和标记显示来自 MySQL 本地数据库的数据。

<html>
<table>
<tr>
<th>field1</th>
<th>field2</th>
<th>field3</th>
</tr>
<?php
$dbh = new PDO("mysql:host=localhost;dbname=dbtest", 'root', 'root');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare("SELECT `fruit_id`, `name`, `variety` FROM fruit");
$sth->execute();
?>
<?php foreach($sth->fetch(PDO::FETCH_ASSOC) as $row) : ?>
<tr>
<td><?php echo $row["fruit_id"]; ?></td>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["variety"]; ?></td>
</tr>
<?php endforeach;?>
</table>

我收到同样的非法字符串偏移错误。另外,我想由于这些原因,我也无法显示我的表格。我是使用 PHP 处理数据库的新手,在发布自己的问题之前,我也确实研究了有关非法字符串偏移错误的其他问题,但由于我的初学者水平的专业知识,我不太能够理解答案。谁能帮我删除错误并显示表格吗?

最佳答案

在 foreach 中使用 $sth->fetchAll(),因为 $sth->fetch() 只会返回单行。

<?php foreach($sth->fetchAll() as $row) : ?>

关于php - 如何解决非法字符串偏移错误并显示以下代码片段中的表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37724332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com