0

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

3
  • Initialize the database connection in opendatabase.php and pass the connection link as a parameter to your function. Commented Mar 11, 2014 at 15:34
  • 1
    It's a scope issue. Your DB connection should be made global (which is not recommended) or passed through the function itself. Commented Mar 11, 2014 at 15:36
  • what error do you get when you dont use include "opendatabase.php"; Commented Mar 11, 2014 at 15:36

4 Answers 4

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

if (mysql_num_rows($result) > 0) {
    // rows found..
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

0

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;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.