非法字符串偏移

时间:2013-09-12 12:27:50

标签: php foreach fetch

$sql = "SELECT images.id, title, image, note 
        FROM news 
        INNER JOIN images ON news.id = images.id_news
        WHERE news.id=?
        ORDER BY images.id DESC";

$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));

$e = $stmt->fetch();

foreach($e[] as $row)
{
    $e[]=array(
        'title'=>$row['title'],
        'image'=>$row['image'],
        'note'=>$row['note']
        );
}

然后我有

Warning: Illegal string offset 'title' in C:\xampp\htdocs\Wazup.mn\inc\functions.inc.php on line 20

Warning: Illegal string offset 'image' in C:\xampp\htdocs\Wazup.mn\inc\functions.inc.php on line 21

Warning: Illegal string offset 'note' in C:\xampp\htdocs\Wazup.mn\inc\functions.inc.php on line 22

2 个答案:

答案 0 :(得分:0)

忽略[]声明中的foreach

foreach($e as $key => $val)
{
    $key=$val
}

但是,更简单,你可以做到

extract($e);

答案 1 :(得分:0)

你可以在fetchAll函数中使用FETCH_COLUMN,然后使用foreach循环

$e = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
foreach($e as $row)
{
    $e=array(
        'title'=>$row['title'],
        'image'=>$row['image'],
        'note'=>$row['note']
        );
}