Forums

How to count rows in the database [SOLVED]

redrings 26 Mar, 2010
Tried searching the forums and found lots of examples, but it's still not working for me so I thought I would see if I could get some help:

I want to count the number of rows in the database for a form, and based on that number either display or not display the form (ie, after 50 registrations do not show the form).

I'm trying this:

<?php
$db =& JFactory::getDBO();
$query = "SELECT * FROM #__chronoforms_inspiretest";
$db->setQuery($query);
$rowx = $db->loadObject();
echo $db->getErrorMsg();
$test = $db->getNumRows();
echo 'Number of rows via getNumRows: ' . $test . '<br />';
echo 'Number of rows via count($rows): ' . count($rows);
?>


There are 3 rows in the database; however, this is the result I'm getting:

Number of rows via getNumRows:
Number of rows via count($rows): 0


Any ideas about what I'm doing wrong? Thanks!
GreyHead 27 Mar, 2010
Hi redrings,

Count is probably zero because you have $rowx in one place and $rows in another.

To get getNumRows to work I think you have to use this sequence to retrieve the count before you get the Results. (From the Joomla Docs How to use the database classes in your script)
$db->setQuery($query);
$db->query();
$num_rows = $db->getNumRows();
print_r($num_rows);
$result = $db->loadRowList();

Bob
Jetsfan 29 Mar, 2010
I wanna show the number of rows in the database at the same page as the form. Do i have to do it the same way? Where do i have to write this code? Is there a possibility to show the result at the (main page) homepage?
Jetsfan 01 Apr, 2010
I did it this way.

<?php
$sql = "SELECT * FROM name_of_your_table";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
echo "$num_rows";
?> 
This topic is locked and no more replies can be posted.