paddy_fields Posted December 5, 2013 Share Posted December 5, 2013 Hi. I was using the method below to count the rows in a table, but I've since learnt I should be using SQL Count. Old method.... //total number of jobs if ($result = $db->query("SELECT * FROM jobBoard")) { $totalJobCount = $result->num_rows; $result->close(); echo $totalJobCount; } I've now changed this to.... //total number of jobs if ($result = $db->query("SELECT count(*) AS jobCount FROM jobBoard")) { $findCount = $result->fetch_assoc(); $totalJobCount = $findCount['jobCount']; $result->close(); echo $totalJobCount; } Is my new method the best way of doing this? It provides the correct result but I'm new to mysqli and I'm not sure if fetch_assoc() is the right way to go? Thanks. Pat. Link to comment https://forums.phpfreaks.com/topic/284566-changing-php-num_rows-method-to-sql-count/ Share on other sites More sharing options...
mac_gyver Posted December 5, 2013 Share Posted December 5, 2013 you can shorten - $findCount = $result->fetch_assoc(); $totalJobCount = $findCount['jobCount']; to be - list($totalJobCount) = $result->fetch_row(); Link to comment https://forums.phpfreaks.com/topic/284566-changing-php-num_rows-method-to-sql-count/#findComment-1461420 Share on other sites More sharing options...
paddy_fields Posted December 5, 2013 Author Share Posted December 5, 2013 That's great, thank you. Just to get my head around that... is $result an array with one value? And then list($totalJobCount) assigns that array item to $totalJobCount? Link to comment https://forums.phpfreaks.com/topic/284566-changing-php-num_rows-method-to-sql-count/#findComment-1461421 Share on other sites More sharing options...
Barand Posted December 5, 2013 Share Posted December 5, 2013 $result->fetch_row() will return an array with 1 item (the count) Link to comment https://forums.phpfreaks.com/topic/284566-changing-php-num_rows-method-to-sql-count/#findComment-1461422 Share on other sites More sharing options...
paddy_fields Posted December 5, 2013 Author Share Posted December 5, 2013 Ok thanks, I understand. Good to know! Link to comment https://forums.phpfreaks.com/topic/284566-changing-php-num_rows-method-to-sql-count/#findComment-1461424 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.