duanpu2272 2013-02-17 09:03
浏览 26
已采纳

mySQLi查询将结果放入数组和不同的DIV中

I want to query the content of multiple (6 in total, IDs 1 to 6) IDs from a mySQL database using mySQLi. After that I want to put the result ("introtext") in different DIVs. At the moment I use the following code (works perfect):

<?php
$q = $db->query("SELECT introtext FROM content WHERE id=1");
$r = $q->fetch_object();
?>
<div id="content1" class="toggle"><?php echo "$r->introtext";?></div>

<?php
$q = $db->query("SELECT introtext FROM content WHERE id=2");
$r = $q->fetch_object();
?>
<div id="content2" class="toggle"><?php echo "$r->introtext";?></div>

<?php
$q = $db->query("SELECT introtext FROM content WHERE id=3");
$r = $q->fetch_object();
?>
<div id="content3" class="toggle"><?php echo "$r->introtext";?></div>

And so on...

How can I optimize this code to query mySQL only once (put the results in array) and assign the different results into the different DIVs?

Cheers Shredder

  • 写回答

3条回答 默认 最新

  • duanfazhun0383 2013-02-17 09:08
    关注

    Good question
    Basically you will need 2 loops
    one to get your array with data:

    <?php
    $data = array();
    $res = $db->query("SELECT id, introtext FROM content ORDER BY id LIMIT 6");
    while($row = $res->fetch_assoc()) {
        $data[$row['id']] = $row['introtext'];
    }
    ?>
    

    You can use whatever SQL to filter out your queries. ORDER BY id LIMIT 6 seems most convenient for the present case "get first 6 ids", as consecutiveness is never guaranteed.

    And then another loop to display

    <? foreach ($data as $id => $introtext): ?>
    <div id="content<?=$id?>" class="toggle"><?=htmlspecialchars($introtext?)></div>
    <? endforeach ?>
    

    By the way, if use not raw Mysqli API but some helper library the PHP part will be reduced to one line:

    <?php
    $data = $db->getIndCol("id","SELECT id, introtext FROM content ORDER BY id LIMIT 6");
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站