gpt4 book ai didi

php - 使用 PDO 语句选择表数据

转载 作者:IT王子 更新时间:2023-10-29 00:31:57 24 4
gpt4 key购买 nike

我有一个通过 mysql_ 选择数据的 php 脚本,但是最近我一直在阅读 PDO 是要走的路,而 mysql_ 正在贬值。现在我将该脚本转换为 PDO。

我的问题是,我没有使用 $_POST 来选择。我只想选择包含所有数据的整个表,所以我输入了这个查询:

$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $query->fetchall(); // or you can just $result = $query as hakre proposed!

然后就像我使用旧的已折旧 mysql_ 版本的脚本一样,我使用 echo 来回显一个包含数据的表。

    echo 
"<table border='2'>
<tr>
<th>ID</th>
<th>A Number</th>
<th>First Name</th>
<th>Last Name</th>
<th>Why</th>
<th>Comments</th>
<th>Signintime</th>
</tr>"
;

foreach($result as $row)
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td><a href=Student.php?studentA_num=" . $row['anum'] . ">" .$row['anum'] . " </a></td>";
echo "<td>" . $row['first'] . "</td>";
echo "<td>" . $row['last'] . "</td>";
echo "<td>" . $row['why'] . "</td>";
echo "<td>" . $row['comments'] . "</td>";
echo "<td>" . $row['signintime'] . "</td>";
echo "<td> <input type=\"button\" value=\"Start Session\"onClick=\accept.php?id=" . $row['id'] . "&start=true></td>";
}

echo "</tr>";
echo "</table>";

现在使用它,我无法在我的表中获得单个输出。

This is all that is being outputted

我的问题是我的选择语句是否遗漏了什么?还是我没有获取任何行?我还在另一个名为 connect.php 的脚本中设置了连接设置,这是 init.php 所需的(在我所有页面的顶部)

编辑:1

编辑了代码,现在它可以工作了,还添加了一张图片来向其他人展示它的外观!希望有人可以将其用于某种用途! This is how it looks!

最佳答案

其实你做的太多了:

$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $dbh->query($query);

有问题的行是:

$result = $dbh->query($query);

http://php.net/pdo.query 联系,参数是一个字符串,其实就是上面你已经使用的SQL字符串,而不是PDO::prepare()调用的结果值。

对于您的简单查询,您可以这样做:

$result = $dbh->query("SELECT * FROM students");

或者如果你喜欢准备:

$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $query;

如果你想在查询中插入变量,后者是一些样板,这就是你准备它的原因。


下一个问题是 foreach 行:

foreach($result as $row);

由于末尾有分号 ;,您将立即终止循环。删除该分号,以便下面的尖括号代码块成为 foreach 循环的主体。

关于php - 使用 PDO 语句选择表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14104429/

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