有没有一种简单的方法来重复php mysql查询?

时间:2011-01-18 23:39:36

标签: php mysql

我希望php有一个小技巧,可以节省100份拷贝>粘贴>更改号码 - 谢谢你看看!

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

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

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

  

$ result = mysql_query(“SELECT * FROM products WHERE manufacturer ='3M'”);
  while($ row = mysql_fetch_array($ result)){
  echo $ row ['manufacturer']。 “”。 $行[ '模型']; }

我正在做的是工作,但有没有办法获得所有制造商的列表然后在列表上运行上面的PHP?

或者也许是我没想过的不同之处?

谢谢你,

(实际输出是按照javascript手风琴进行的 - 所以在单页上显示它不是问题)

2 个答案:

答案 0 :(得分:2)

独特的制造商

SELECT manufacturer
FROM products
GROUP BY manufacturer

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

编辑这应该做你想要的(或者至少是你玩的好基础)。这将把制造商作为手风琴的标题,然后在其中列出模型。

$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>';
}

同样,如果你可以更清楚,可能会得出一个更好的解决方案。

答案 1 :(得分:2)

如果你想用1个查询从你的数据库中获取所有结果,你可以简单地获取all而不使用where子句并按制造商排序,这样你就可以在php中“分组”行。我明白这是你想要的,无论如何你应该分页。

$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']; 

}