$res_seven = $stmt_seven->fetchAll [...]
foreach($res as ...
什么是 $res?
foreach( $resultOfFetchAll as $val) {
foreach($val as $val1) {
// now $val1 is the value of a single column, i.e. a scalar or a string
// but you're trying to access as if it was a row / array
}
}
您可以简单地将PDOStatement对象本身传递给 foreach,而不是使用 fetchAll() 然后迭代该数组,因为它实现了可遍历接口。例如
<?php
function foo($db) {
$stmt = $db->query('SELECT img, description FROM Videos ORDER BY date LIMIT 10', PDO::FETCH_ASSOC);
foreach( $stmt as $row ) {
echo $row['img'], ' - ', $row['description'], "<br />\n";
}
if ( 0===$stmt->rowCount() ) {
echo "no data yet<br />\n";
}
echo "---<br />\n";
}
$db = new PDO('sqlite::memory:', null, null);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
setup($db, false);
foo($db);
setup($db, true);
foo($db);
// boilerplate/data-source for self-contained example
function setup($pdo, $populate) {
if ( !$populate ) {
$pdo->exec('
CREATE TABLE Videos (
img,
description,
date
)
');
}
else {
$stmt = $pdo->prepare('INSERT INTO Videos (img,description,date) VALUES (?,?,?)');
for($i=1; $i<21; $i++) {
$stmt->execute(array(
sprintf('img%02d', $i),
sprintf('desc%02d', $i),
sprintf('2012-01-%02d 12:00:00', $i)
));
}
}
}
印刷
no data yet<br />
---<br />
img01 - desc01<br />
img02 - desc02<br />
img03 - desc03<br />
img04 - desc04<br />
img05 - desc05<br />
img06 - desc06<br />
img07 - desc07<br />
img08 - desc08<br />
img09 - desc09<br />
img10 - desc10<br />
no data yet<br />
---<br />