如何用php获取mysql数据库的行数

时间:2014-03-11 15:23:18

标签: php mysql sql database

我想用一个语句或一个函数

获取mysql数据库表的行数
include "opendatabase.php"; //opens database

while (NUMBEROFROWS > 0){
    //do something
}

NUMBEROFROWS应该替换为返回行数的语句

我已经尝试过创建一个功能

function getRowNumber(){
    $query = "SELECT COUNT(*) FROM  `votes`";
    $result = mysql_query($query, $connect);

    list($length) = mysql_fetch_row($result);
    return $length;

}

但如果我不将include "opendatabase.php";放入其中,则无效。

我做错了什么

4 个答案:

答案 0 :(得分:1)

问题是include "opendatabase.php";在另一个范围内运行,如此处所述

http://www.php.net/manual/en/language.variables.scope.php

函数

中缺少global $connect

答案 1 :(得分:1)

$result = mysql_query("SELECT * FROM tablename");

if (mysql_num_rows($result) > 0) {
    // rows found..
}

答案 2 :(得分:0)

你走了:

function num(){
 $data = mysql_query("SELECT * FROM table");
  if(mysql_num_rows($data) > 0){
    while($row = mysql_fetch_assoc($data)){
      // do something with your data..
    }
  }
}

答案 3 :(得分:0)

这对你有用吗?

  function getRowNumber()
{
   $query = "SELECT COUNT(*) as counts FROM  `votes`";
   $result = mysql_query($query, $connect);
   $row = mysql_fetch_array($result);
   $counts = $row['counts'];
return $counts;

}