从php的mysql表中selectcount(*)
我能够获得MySQL的查询结果的值和行。
但是我正在努力获得查询的单一输出。 例如:
$result = mysql_query("SELECT COUNT(*) FROM Students;");
我需要显示结果。 但是我没有得到结果。
我尝试了以下方法:
-
mysql_fetch_assoc()
-
mysql_free_result()
-
mysql_fetch_row()
但是我没有成功显示(获得)实际的价值。
您需要使用as
关键字别名聚合,以便从mysql_fetch_assoc
调用它
$result=mysql_query("SELECT count(*) as total from Students"); $data=mysql_fetch_assoc($result); echo $data['total'];
如果你只需要价值:
$result = mysql_query("SELECT count(*) from Students;"); echo mysql_result($result, 0);
$result = mysql_query("SELECT COUNT(*) AS `count` FROM `Students`"); $row = mysql_fetch_assoc($result); $count = $row['count'];
试试这个代码。
请开始使用PDO。
从PHP 5.5.0开始,不build议使用mysql_ *,并且将在7中完全删除。现在让我们更容易升级并开始使用它。
$dbh = new \PDO($dsn, $user, $password); $sth = $dbh->prepare('SELECT count(*) as total from Students'); $sth->execute(); print_r($sth->fetchAll());
$num_result = mysql_query("SELECT count(*) as total_count from Students ") or exit(mysql_error()); $row = mysql_fetch_object($num_result); echo $row->total_count;
$howmanyuser_query=$conn->query('SELECT COUNT(uno) FROM userentry;'); $howmanyuser=$howmanyuser_query->fetch_array(MYSQLI_NUM); echo $howmanyuser[0];
经过这么多小时以后,精彩:)
我认为这是更好的答案。
$query = "SELECT count(*) AS total FROM table_name"; mysql_select_db('database_name'); $result = mysql_query($query); $values = mysql_fetch_assoc($result); $num_rows = $values['total']; echo $num_rows;
$abc="SELECT count(*) as c FROM output WHERE question1=4"; $result=mysqli_query($conn,$abc); if($result) { while($row=mysqli_fetch_assoc($result)) { echo $row['c']; } }
在这里它计数question1列中出现的次数,它的工作完全
你也可以使用这个并升级到
mysqli_
(停止使用mysql_*
扩展…)
$result = mysqli_query($conn, "SELECT COUNT(*) AS `count` FROM `Students`"); $row = mysqli_fetch_array($result); $count = $row['count']; echo'$count';
$qry_appr = "SELECT COUNT(*) FROM comments WHERE admin_panel_id ='$id' AND status = 'ON'"; $qry_data = mysqli_query($con, $qry_appr); $approve_count = mysqli_fetch_array($qry_data); $toatalCount = array_shift($approve_count); echo $toatalCount;
这也将罚款但是这是通过移取数组返回0的索引值。 欢迎所有
使用mysql v5.7.20,以下是我如何能够从使用PHP v7.0.22的表中获取行计数:
$query = "select count(*) from bigtable"; $qresult = mysqli_query($this->conn, $query); $row = mysqli_fetch_assoc($qresult); $count = $row["count(*)"]; echo $count;
第三行将返回一个如下所示的结构:
array(1) { ["count(*)"]=>string(4) "1570" }
在这种情况下,结束echo语句将返回:
1570
如果你只想计数值,你可以做简写:
$cnt = mysql_num_rows(mysql_query('select * from students'));