dongzan7016 2014-07-02 16:10
浏览 56
已采纳

MySQL / PHP:从Database中的1列中获取多个值

I'm trying to select multiple values from 1 column in my MySQL database. I have a Table 'products' with a column 'category'. Categories: Home, Garden, Cars, Bicycle etc. I want to fetch the number of products with these categories for statistics. It sounds simple but I can only get it done with allot of code. I want all of these categories to be variables so I only have to put my variables in my statistics engine to do the calculation. Right now this is my code to fetch the number of products with category 'Garden':

$query = "SELECT * FROM products WHERE category='Garden'";
$result= mysql_query($query);
$row   = mysql_fetch_array($result);

echo "$row[category]";

Repeating this for every category does 't seem right to me.. Does anyone understand my question and have a solution?

  • 写回答

3条回答 默认 最新

  • doqs8936 2014-07-02 16:11
    关注

    try this

       $query = "SELECT *, count(*) as counts FROM products group by category";
       $result= mysql_query($query);
       while($row   = mysql_fetch_array($result))
       {
       echo $row['category']." ". $row['counts'];
    
       }
    

    you have to use while to fetch multiple categories.

    you need to group by category to get distinct categories.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致