$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
}
}
fetchAll()を使用してその配列を反復処理する代わりに、PDOStatementオブジェクト自体をforeachに渡すことができます。これは、トラバース可能なインターフェイスを実装しているためです。例えば
<?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 />