$duyuru1 = $PDO->prepare("SELECT * FROM duyurular WHERE id = ?");
$duyuru1->execute(array('1'));
$duyuru1->fetchAll();
$duyuru2 = $PDO->prepare("SELECT * FROM duyurular WHERE id = ?");
$duyuru2->execute(array('2'));
$duyuru2->fetchAll();
$duyuru3 = $PDO->prepare("SELECT * FROM duyurular WHERE id = ?");
$duyuru3->execute(array('3'));
$duyuru3->fetchAll();
$duyuru4 = $PDO->prepare("SELECT * FROM duyurular WHERE id = ?");
$duyuru4->execute(array('4'));
$duyuru4->fetchAll();
$duyuru5 = $PDO->prepare("SELECT * FROM duyurular WHERE id = ?");
$duyuru5->execute(array('5'));
$duyuru5->fetchAll();
第72行:<?php echo $duyuru1['baslik'] ?>
致命错误:不能在第72行的index.php中使用PDOStatement类型的对象作为数组
答案 0 :(得分:1)
试试这个:
// set exception handling to report SQL errors
$PDO->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
try {
// prepare statement once
$stmt = $PDO->prepare("SELECT * FROM duyurular WHERE id = ?");
// execute statement & fetch data for first row as associative array.
$stmt->execute(array('1'));
$duyuru1 = $stmt->fetch(PDO::FETCH_ASSOC);
// Execute same statement again with new argument. Fetch data
$stmt->execute(array('2'));
$duyuru2 = $stmt->fetch(PDO::FETCH_ASSOC);
// repeat for remaining arguments.
$stmt->execute(array('3'));
$duyuru3 = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->execute(array('4'));
$duyuru4 = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->execute(array('5'));
$duyuru5 = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
// Exception lands here. Report problem and exit.
echo $e->getMessage();
exit;
}
...后...
<?php echo $duyuru1['baslik'] ?>
这假设id
在您的表中是唯一的 - 如果不是,您需要更多代码来检索剩余的行。
这也是一种从数据库中检索多行的笨拙方法。您可以更好地改进查询并立即将所有行检索到数组中,但这是一个单独的问题。