[英]Looping through PDO result of table
I have a table named events
like this with 3 entries: 我有一个名为events
的表,带有3个条目:
-------------------------------------
| Name | Description | Image | Date |
-------------------------------------
I am calling a PDO query such as below: 我正在调用如下的PDO查询:
`Connection handled in a class`
$stmt = $DB_con->prepare("SELECT Name, Description, Image, Date FROM events");
$stmt->execute();
$events = array();
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$events = $row;
}
}
And later in my code when I call upon $events
: 然后在我的代码中,当我调用$events
:
for ($x = 0; $x < count($events); $x++) {
echo $events[$x];
}
But all that returns for me is: 但是对我来说,所有回报是:
ArrayArrayArray ArrayArrayArray
First of all, look at this statement here in the while()
loop, 首先,在while()
循环中查看此语句,
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$events = $row;
^ it should be $events[]
}
In each iteration you're assigning the array to $events
, not appending it. 在每次迭代中,您都将数组分配给$events
,而不是附加数组。
And second, when you do this echo $events[$x];
其次,当您执行此操作时, echo $events[$x];
it shows ArrayArrayArray because $events[$x]
is actually an array, not a string. 它显示ArrayArrayArray,因为$events[$x]
实际上是一个数组,而不是字符串。
So your code should be like this: 因此,您的代码应如下所示:
// your code
$events = array();
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$events[] = $row;
}
}
for ($x = 0; $x < count($events); $x++) {
echo $events[$x]['Name'] . "<br />";
// like that you can do this
// echo $events[$x]['Description'];
// echo $events[$x]['Image'];
// echo $events[$x]['Date'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.