PHP和Mysqli获取count(distinct())查询的值

时间:2015-04-23 16:18:58

标签: php mysql mysqli count distinct

我在mysql中有一个名为gsm的db表,有2列,LAC和NAME。

所以我试图计算DB中存储了多少不同的LAC并检索php值以便进一步使用。我正在使用mysqli

我有:

$sql = "select count(distinct lac) from gsm ");

如何将该查询存储到php中的变量?

3 个答案:

答案 0 :(得分:1)

//conection:
$link = mysqli_connect("www.mywebsite.com","user","password","dataname") or die("Error " . mysqli_error($link));

//consultation:
$query = "SELECT COUNT(DISTINCT alias) as visitors FROM Visits where time BETWEEN timestamp(DATE_SUB(NOW(), INTERVAL 1 HOUR)) AND timestamp(NOW())";

//execute the query.
$result = $link->query($query) or die("Error in the consult.." . mysqli_error($link));
$row = mysqli_fetch_array($result);

//display information:
// The text to draw
$text = $row['visitors'];

答案 1 :(得分:0)

您可以使用以下代码进行检查,但是我没有对其进行测试,但我确信它可以正常使用。

 # Init the MySQL Connection
    if (!( $db = mysql_connect('localhost', 'root', '') ))
        die ('Failed to connect to MySQL Database Server - #'.mysql_errno ().': '.mysql_error ());
    if (!mysql_select_db('ram'))
        die ('Connected to Server, but Failed to Connect to Database - #'.mysql_errno ().': '.mysql_error ());
    # Prepare the SELECT Query
    $sql = "select count(distinct lac) as LAC from gsm ";
    if (!( $selectRes = mysql_query($sql) )) {
        echo 'Retrieval of data from Database Failed - #' . mysql_errno() . ': ' . mysql_error();
    } else if (mysql_num_rows($selectRes) == 0) {

        echo 'No Any Record Returned';
    } else {
        while ($row = mysql_fetch_assoc($selectRes)) {
            echo $row['LAC'];
        }
    }

答案 2 :(得分:0)

为了在mysqli中执行此操作,您需要

$count = $DB->query("SELECT COUNT( DISTINCT(LAC)) FROM gsm");
$row = $count->fetch_row();
echo 'LAC appears '. $row[0] . ' times in total.';

所以现在你可以将$row[0]用于你想要的任何其他内容。它是数据库中LAC的唯一值的数量。