更新 我使用了以下查询:
$act1 = $dbh->prepare("(SELECT Title, start_date FROM service_o ORDER BY start_date DESC limit 2) UNION (SELECT Title, Start_Date FROM research_o ORDER BY start_date DESC limit 2) UNION (SELECT Title, Start_Date FROM intern_o ORDER BY start_date DESC limit 2) UNION (SELECT Title, Start_Date FROM participate_o ORDER BY start_date DESC limit 2)");
$act1->execute();
$act1->fetchAll();
$result = $act1->fetchall(PDO::FETCH_ASSOC);
是否绝对有必要使用var_dump?此外,我在使用它时得到一个未定义的偏移错误:
echo $result[0]['Title']
答案 0 :(得分:1)
使用execute
,然后使用fetchAll
将所有结果作为数组返回。
$act1 = $dbh->prepare("SELECT Title, start_date FROM table1 ORDER BY start_date DESC limit 2
UNION
SELECT Title, Start_Date FROM research_o ORDER BY table2 DESC limit 2
UNION
SELECT Title, Start_Date FROM intern_o ORDER BY table3 DESC limit 2
UNION
SELECT Title, Start_Date FROM participate_o ORDER BY table4 DESC limit 2 ");
$act1->execute();
$result = $act1->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
您的数组将采用如下结构:
$result = [
'0' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
'1' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
'2' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
'3' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
'4' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
'5' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
'6' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
'7' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
];
这意味着您可以通过调用:
来访问面板中数组的每个元素echo $result[0]['Title'] . ' - ' . $result[0]['Start_Date'];
或者,如果您想循环浏览它们并立即显示所有内容:
foreach ($result as $row) {
echo '<div class="panel">' . $row['Title'] . ' - ' . $row['Start_Date'] . '</div>';
}
详细了解execute
此处显示的内容,以便从查询中获取数据:http://php.net/manual/en/mysqli-stmt.execute.php
执行先前使用mysqli_prepare()函数准备的查询。