【问题标题】:PHP and Mysqli getting value of a count(distinct()) query [duplicate]PHP和Mysqli获取计数(distinct())查询的值[重复]
【发布时间】:2015-04-23 16:18:58
【问题描述】:

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

所以我试图计算有多少不同的 LAC 存储在数据库中并检索一个 php 值以供进一步使用。我正在使用 mysqli

我有:

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

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

【问题讨论】:

  • 阅读此处标记的答案 - stackoverflow.com/questions/4331353/…
  • @Fransisco Castillo,你为什么最后加了一个额外的括号?
  • @Fransisco Castillo 你得到答案还是我应该在这里添加代码?
  • @hardikbhavsar 如果可以请添加代码,那将是惊人的!谢谢!
  • @beingsunny 抱歉,打错了!

标签: php mysql mysqli count distinct


【解决方案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'];

【讨论】:

    【解决方案2】:

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

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

    所以现在你可以使用$row[0] 来处理你在php 中想要的任何东西。它是您的数据库中 LAC 的唯一值的数量。

    【讨论】:

      【解决方案3】:

      你可以检查下面的代码,但是它没有经过我的测试,但我确信它会工作。

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

      【讨论】:

        猜你喜欢
        • 2013-12-28
        • 2013-02-23
        • 1970-01-01
        • 1970-01-01
        • 2020-07-28
        • 1970-01-01
        • 2020-09-09
        • 2018-05-19
        • 2023-04-09
        相关资源
        最近更新 更多