如何组合两个相同的查询(fetch和fetchall)

时间:2017-07-19 08:27:21

标签: php mysql sql fetch

我有两个查询(完全相同),我想合并

第一个查询:

$stmt = $bdd->prepare('SELECT *, DATE_FORMAT(date_parcel,"%d/%m/%Y") AS formatted_date from validated WHERE name = :name group by age order by age DESC');
$stmt ->execute(array(
  ':name' => $_GET['name']
  ));
$orders = $stmt ->fetchall();

它允许我执行我的foreach 循环将所有数据放入HTML表格

第二个问题:

$infos = $bdd->prepare('SELECT *, DATE_FORMAT(date_parcel,"%d/%m/%Y") AS formatted_date from validated WHERE name = :name group by age order by age DESC');
$infos ->execute(array(
  ':name' => $_GET['name']
  ));
$info = $infos ->fetch();

这与完全相同,但它允许我在foreach循环之前使用数据来显示信息。

代码如下所示:

<div class="panel panel-default">
    <div class="panel-body">
        <center><h3><?php echo ucwords(strtolower($info['data5'])). ' - ' . $info['data6']; ?></h3></center>
        ....
    </div>
</div>

....

<tbody>
    <?php foreach ($orders as $row) { ?>
    <tr>
        <td colspan="1"><?php echo $row['data1'] ?></td>
        <td colspan="1"><?php echo $row['data2'] ?></td>
        <td colspan="1"><?php echo $row['data3'] ?></td>
        <td colspan="1"><?php echo $row['data4'] ?></td>
    </tr>
    <?php } ?>
</tbody>

所以我希望能够使用单个请求,我该怎么办? 谢谢

2 个答案:

答案 0 :(得分:1)

我认为你可以像这样使用

$stmt = $bdd->prepare('SELECT *, DATE_FORMAT(date_parcel,"%d/%m/%Y") AS formatted_date from validated WHERE name = :name group by age order by age DESC');
$stmt ->execute(array(
  ':name' => $_GET['name']
));
$orders = $stmt ->fetchall();
$info = $stmt ->fetch();

也许它有效......不确定。

答案 1 :(得分:1)

fetchAll返回一个数组,以便您可以轻松地使用它来获取特定的行:

$stmt = $bdd->prepare('SELECT *, DATE_FORMAT(date_parcel,"%d/%m/%Y") AS formatted_date from validated WHERE name = :name group by age order by age DESC');
$stmt ->execute(array(
  ':name' => $_GET['name']
  ));
$orders = $stmt ->fetchall();
$info = $orders[0];