统计php查询数据库

时间:2014-07-11 20:57:41

标签: php mysql mysqli

我必须根据最多的选票制作游戏列表。 然后我必须使用查询计数到我的db.Ho尝试下面的代码但没有任何反应。帮帮我

$con=mysqli_connect("localhost","root","","blog");
            // Check connection
            if (mysqli_connect_errno()) {
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
            }

            $result = mysql_query($con,"SELECT COUNT(nomeGioco) FROM voto");


            mysqli_close($con);

2 个答案:

答案 0 :(得分:2)

如果您想获取游戏名称列表以及该名称在表格中显示的次数,您将要开始使用以下查询:

SELECT nomeGioco, COUNT(nomeGioco) num_count 
    FROM voto 
    GROUP BY nomeGioco 
    ORDER BY num_count DESC

为了将其细分,GROUP BY将根据“nomeGioco”聚合行。列和" ORDER BY列DESC"将按num_count降序排序您的行(让游戏在顶部的表格中发生最多)。

然后,您可以使用mysqli_fetch_all从结果对象中获取所有结果,如下所示:

$query = 'SELECT nomeGioco, COUNT(nomeGioco) num_count '
        . 'FROM voto '
        . 'GROUP BY nomeGioco '
        . 'ORDER BY num_count DESC';

$con = mysqli_connect("localhost","root","","blog");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con, $query);

$contents = mysqli_fetch_all($result, MYSQLI_ASSOC);

mysqli_free_result($result);
mysqli_close($con);

// The contents of the query
var_dump($contents);

// Go through each row and append them to a string to output in HTML
$toHTML = '';
if(is_array($contents)) {
    foreach($contents as $row) {
        $toHTML .= $row['nomeGioco'] . ': ' . $row['num_count'] . ' votes<br />';
    }
}

echo $toHTML;

答案 1 :(得分:0)

进行查询

$con = New mysqli("localhost","root","","blog");
if (!$conn)
{
die("Database connection failed: " . mysqli_error());
}
$query = $con->query("SELECT COUNT(`nomeGioco`) FROM `voto`");
$result = $query->fetch_assoc();
echo $result['COUNT(nomeGioco)'];
$con->close;