计算数据库中的所有值

时间:2013-06-05 13:58:08

标签: php count

  <?php
    session_start();
    include "config.php";
    if(isset($_POST['sub'])) {
        if(!empty($_POST["column"])) {
              $a = $_POST['column'];  // column name 

    } else {
              $a ="";
              echo "please click on the right input";
    }
    $r="select '".$a."' , count(*) as '".$a."' from emc_leadgen group by '".$a."' ";
    $t=mysql_query($r);
    if (!$t) 
    {
        $message = 'ERROR:' . mysql_error();
        return $message;
    }
    else
    {
        $i = 0;
        ?>
    <html xmlns:o="urn:schemas-microsoft-com:office:office"
    xmlns:x="urn:schemas-microsoft-com:office:excel"
    xmlns="http://www.w3.org/TR/REC-html40">
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    WELCOME <?=$_SESSION['user']?></br>
    <title> emc promo 1</title>
    <meta http-equiv="Content-type" content="text/html;charset=utf-8" />
    </head>
    <body>
    <?PHP
        echo '<html><body><table><tr>';
        while ($i < mysql_num_fields($t))
        {
            $meta = mysql_fetch_field($t);
            echo '<td>' . $meta->name . '</td>';
            $i = $i + 1;
        }
        echo '</tr>';

        $i = 0;
        while ($row = mysql_fetch_row($t)) 
        {
            echo '<tr>';
            $count = count($row);
            echo $count;
            $y = 0;
            while ($y < $count)
            {
                $c_row = current($row);
                echo '<td>' . $c_row . '</td>';
                echo "</br>";
                next($row);
                $y = $y + 1;
            }
            echo '</tr>';
            $i = $i + 1;
        }
        echo '</table></body></html>';
        mysql_free_result($t);
    }

    }{echo "there is no data";}*/
    }
    ?``>
    </body>
    </html>

//我在查询中使用COUNT .........在我的结果中我得到一个数组格式但我需要数据库中的唯一值。它将计算数据库中的值和然后像我在下面写的那样显示它     我需要这个结果     新德里= 4     兰契= 2     法里达巴德= 3     但我得到city = 9 //

1 个答案:

答案 0 :(得分:0)

您是否可以使用数据库结构来更好地理解数据。

如果我正在思考你想要得到一个值在数据库中的行号,这应该有效:

SELECT a.name, @curRow := @curRow + 1 AS row_number FROM contacts a JOIN (SELECT @curRow := 0) r

这将输出一个名为'row_number'的列,其中包含实际的行号 - (我刚刚使用了我运行的本地数据库来试用它)

编辑:

此查询将返回城市以及使用该城市分配的用户数:

SELECT city.name, COUNT(*) AS user_count FROM users INNER JOIN city ON users.city = city.id GROUP BY city

我做了如下测试:

$conn = mysqli_connect('localhost', 'root', 'root', 'test');
$query = mysqli_query($conn, "SELECT city.name, COUNT(*) AS user_count FROM users INNER JOIN city ON users.city = city.id GROUP BY city");
print '<ul>';
while($row = mysqli_fetch_array($query)):
    print '<li>'.$row['name'].' - Users = '.$row['user_count'].'</li>';
endwhile;
print '</ul>';

输出如下:

  • 伦敦 - 用户= 1
  • Southampton - Users = 3
  • 曼彻斯特 - 用户= 2
相关问题