Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count numbers of row of sql query in joomla and display it?

Tags:

sql

php

joomla

My sql query is this one:

SELECT COUNT(*) AS NumberOfOrders FROM table_products where published = 1;

Joomla use Jdatabase to play with tables. I found this on internet:

$db = JFactory::getDbo(); 
 $query = $db->getQuery(true); 
 $query->select(array('name', 'email', 'username')) 
   ->from($db->quoteName('#__my_users')) 
   ->where($db->quoteName('name') . ' LIKE '. $db->quote('\'%SMITH%\'')); 
 $db->setQuery($query); 

 // get the count 
 $my_count = $db->getNumRows(); 

 // retrieve the data 
 $rows = $db->loadObjectList(); 

 echo $my_count; 

So I try to modify this example for my query:

$db = JFactory::getDbo(); 
 $query = $db->getQuery(true); 
 $query->select(array('id')) 
   ->from($db->quoteName('#__table_products')) 
   ->where($db->quoteName('published') . ' LIKE '. $db->quote('1')); 

 $db->setQuery($query); 

 // get the count 
 $my_count = $db->getNumRows(); 

 // retrieve the data 
 $rows = $db->loadObjectList(); 

But it doesn't work. I get empty result. What is wrong?

Someone can help me please?

Regards

like image 991
Nino Avatar asked Jan 15 '15 16:01

Nino


People also ask

How do I count rows in SQL query?

SQL COUNT(), AVG() and SUM() FunctionsThe COUNT() function returns the number of rows that matches a specified criterion.

How do you show the number of rows?

Just click the column header. The status bar, in the lower-right corner of your Excel window, will tell you the row count. Do the same thing to count columns, but this time click the row selector at the left end of the row.

How do I count a query in a selection?

SQL SELECT COUNT(*) function SQL SELECT statement can be used along with COUNT(*) function to count and display the data values. The COUNT(*) function represents the count of all rows present in the table (including the NULL and NON-NULL values).

Can you list the ways to get the count of records in a table?

With the help of the SQL count statement, you can get the number of records stored in a table.


2 Answers

$db->setQuery($query);
$my_count = $db->query();
$my_count = $db->getNumRows();
like image 168
Anup Chauhan Avatar answered Oct 21 '22 12:10

Anup Chauhan


Try this way to COUNT number of rows, but i am not sure about

$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('COUNT(*)');
$query->from($db->quoteName('#__table_products'));
$query->where($db->quoteName('published') . ' LIKE '. $db->quote('\'%1%\''));

$db->setQuery($query);
$count = $db->loadResult();

SEE MORE:https://docs.joomla.org/Selecting_data_using_JDatabase

like image 2
Always Sunny Avatar answered Oct 21 '22 13:10

Always Sunny