简体   繁体   中英

PHP and Mysqli getting value of a count(distinct()) query

I have a db table in mysql called gsm, with 2 columns, LAC and NAME.

So I am trying to count how many different LAC are stored in the DB and retrieve a php value to further use. I am using mysqli

I have:

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

How do I store that query into a variable in php?

//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'];

In order to do this in mysqli, you need

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

So now you can use $row[0] for whatever else you want in php. It is the number of unique values of LAC in your database.

you can check with the below code , however its not tested from my end but im sure that it would work.

 # 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'];
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM