Reputation: 2290
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
Reputation: 4409
$result = mysql_query("SELECT * FROM tablename");
if (mysql_num_rows($result) > 0) {
// rows found..
}
Upvotes: 1
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
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
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