Friedrich
Friedrich

Reputation: 2290

how to get the number of rows of mysql db with php

i would like to get the number of rows of a mysql database table with one single statement or a function

include "opendatabase.php"; //opens database

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

the NUMBEROFROWS should be replaced with the statement that returns the number of rows

i already tried to create a function

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

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

}

but it does not work if i dont put the include "opendatabase.php"; in it.

what am i doing wrong

Upvotes: 0

Views: 82

Answers (4)

Vincent
Vincent

Reputation: 4409

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

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

Upvotes: 1

echo_Me
echo_Me

Reputation: 37233

would this work for you ?

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

}

Upvotes: 0

Friedrich
Friedrich

Reputation: 2290

the problem is that include "opendatabase.php"; runs in another scope like described here

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

there is a global $connect missing within the function

Upvotes: 1

Zy0n
Zy0n

Reputation: 785

Here you go:

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..
    }
  }
}

Upvotes: 0

Related Questions