【问题标题】:Is there a simple way to repeat a php mysql query?有没有一种简单的方法来重复一个 php mysql 查询?
【发布时间】:2011-01-19 07:54:51
【问题描述】:

我希望 php 有一个小技巧可以为我节省 100 次复制>粘贴>更改编号 - 感谢您查看!

我在 MySQL 数据库中有一个相对较大的数据集。

只有两列:模型(大约 7000 个唯一条目)和制造商(大约 100 个唯一条目,即模型来自仅 100 个不同的制造商)

目前(好吧,因为我正在以非常缓慢、重复的方式编写),我有一个庞大的 PHP 数据库查询列表:

$result = mysql_query("SELECT * FROM products WHERE Manufacturer ='3M'");
while ($row = mysql_fetch_array($result)) {
回声 $row['manufacturer'] 。 “”。 $row['model']; }

我正在做的是工作,但也许有一种方法可以获取所有制造商的列表,然后在列表中运行上面的 php?

或者可能是我没有想到的不同的东西?

谢谢大家,

(实际输出是在 javascript 手风琴中完成的 - 因此在单个页面上显示它不是问题)

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    独特的制造商

    SELECT manufacturer
    FROM products
    GROUP BY manufacturer
    

    但我不确定你想要的最终结果是什么。您能否详细说明一下,我会提供更简洁的答案?

    EDIT 这应该可以满足您的需求(或者至少是您玩的一个很好的基础)。这会将制造商作为手风琴的标题,然后列出其中的型号。

    $sql = "SELECT * FROM products ORDER BY manufacturer,product";
    $lastMfg = null;
    if (($result = mysql_query($sql)) !== false)
    {
      echo '<div id="accordion">';
      while (($row = mysql_fetch_array($result)) !== false)
      {
        if ($row['manufacturer'] != $lastMfg)
        {
          if (!is_null($lastMfg))
            echo '</div>';
          echo '<h3><a href="#">'.$row['manufacturer'].'</a></h3>';
          echo '<div>';
          $lastMfg = $row['manufacturer'];
        }
        echo '<p>'.$row['model'].'</p>';
      }
      echo '</div></div>';
    }
    else
    {
      echo '<p>MySQL Error: Unable to fetch products</p>';
    }
    

    再一次,如果你能更清楚一些,或许可以得出一个更好的解决方案。

    【讨论】:

    • 谢谢布拉德,抱歉应该更清楚预期的最终结果。基本上我想要一个制造商的大名单,当你点击其中一个制造商时,它会展开以显示所有可用的型号。您的代码完美地显示了其制造商下的所有模型,但在理解代码的层次结构方面仍然没有问题(即找出放置 h1 手风琴头的位置)
    • 经过更多的折腾,我已经开始工作了。非常感谢,你摇滚!
    【解决方案2】:

    如果你想用 1 个查询从你的数据库中获取所有结果,你可以简单地获取所有没有 where 子句和制造商排序的结果,这样你就可以在 php.ini 中“分组”行。我知道这是您想要的,无论如何您都应该分页。

    $result = mysql_query("SELECT * FROM products ORDER BY manufacturer ASC;" );
    
    $last_manufacturer = false; 
    
    while ($row = mysql_fetch_array($result)) {
    
    if ($last_manufacturer !== $row['manufacturer']) {
     //we got a different manufacturer since we ordered in alphabetical order
        $last_manufacturer = $row['manufacturer'];
        #... do something like put an separator between manufacturers
        # in this example we put a title, you should put the accordion markup or something similar
        echo "<h1> Manufacturer:", $row['manufacturer']  ,"</h1>";
    
    }
    echo $row['manufacturer'] . " " . $row['model']; 
    
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-14
      • 1970-01-01
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 2017-01-25
      • 2022-11-10
      • 2011-11-03
      相关资源
      最近更新 更多