PHP MySQL短查询assoc代码 [英] PHP MySQL short query assoc code

查看:105
本文介绍了PHP MySQL短查询assoc代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要查询和这样的许多查询

I need to query and assoc many queries like this

<?php 
$datacenter=mysqli_connect('localhost','user','pass','db');

db连接,现在我们计算多少个选项1和2和3

db connection, now we count how many voted option 1 and 2 and 3

 $r11=mysqli_query($datacenter, "SELECT COUNT(firstvote) AS `total1` 
FROM `votes` WHERE `firstvote` = '1' ");
    $r11r=mysqli_fetch_assoc($r11);


    $r12=mysqli_query($datacenter, "SELECT COUNT(firstvote) AS `total2` 
FROM `votes` WHERE `firstvote` = '2'");
    $r12r=mysqli_fetch_assoc($r12);

    $r13=mysqli_query($datacenter, "SELECT COUNT(firstvote) AS `total3` 
FROM `votes` WHERE `firstvote` = '3'");
    $r13r=mysqli_fetch_assoc($r13);
    ?>

现在我们回应结果,显示多少票选的选项1,2和3

now we echo the result to display how many voted option 1, 2 and 3

<?php echo number_format($r11r['total1'],0,',','.'); ?>
<? php echo number_format($r12r['total2'],0,',','.'); ?>
<? php echo number_format($r13r['total3'],0,',','.'); ?>

有没有办法使这段代码更短?我是新的PHP

Is there any way to make this code shorter ? I am new to PHP

推荐答案

foreach(array(1,2,3) as $firstvote){
  $res=mysqli_query($datacenter, "SELECT COUNT(firstvote) AS `total` 
                                  FROM `votes` WHERE `firstvote` = '$firstvote' ");
  $r[$firstvote]=mysqli_fetch_assoc($res);
 }

foreach($r as $set){
  echo number_format($set['total'],0,',','.'); 
}

仅限高额投票:

$r['total']=0;
foreach(array(1,2,3) as $firstvote){
  $res=mysqli_query($datacenter, "SELECT COUNT(firstvote) AS `total` 
                                  FROM `votes` WHERE `firstvote` = '$firstvote' ");
  $tmp=mysqli_fetch_assoc($res);
  $r=max($tmp['total'],$r['total']);
 }


 echo number_format($r,0,',','.'); 

因为我现在不知道你真正想做什么,这是一个解决方案,的所有结果。但你应该这样做iwth你的SQL查询。添加 ORDER BY总共LIMIT 1个

since i dont now what you really want to do, this is a solution to get only the highest value of all results. But you should do this iwth your SQL query. add something like ORDER BY total LIMIT 1

这篇关于PHP MySQL短查询assoc代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆