简体   繁体   中英

How to manage many queries on 1 page?

What would be the best way to manage more than 1 query on a page. I am using 4 different queries on one page all of which are just using the variable $query in sequence, so like each query on the page is situated in different areas and as the page loads from top to bottom each query is completed.

I have placed each query in a separate file and included it in the area where i am echoing the data. Is this bad? Should i place them all in one file and use a separate variable for each queries eg $result 1, $row1 then for second query $result 2, $row2 so on so fourth.

Thanks

Forums, online cart programs and the such will often have 10 or 20+ queries per page. 4 is not ganna kill you straight up.

Personally i don't think it's a good idea to use always the same variable for a query, especially for results that should have meaningful names like $numberOfMessages, $countUsers ... remember that the most important thing is that your code is readable by others who might have to mantain it. Spend a little time to write meaningful name for variables.

Speaking of queries, i think it's not a problem to have 4 queries on one page, just make sure that the queries just retrieve the data you want...spend some time optimizing the queries because fetching a lot of data from mysql is a performance killer.

EDIT

for example i use:

//import the db configuration
require_once (JPATH_COMPONENT . DS . 'libs/confDbSugarcrm.php');
$db =& JFactory::getDBO();
//list your queries (i use joomla classes in this example)

$sqlUsers = "select id, name from table_users";
$db->setQuery($sqlUsers); 
$usersIdName = $db->loadObjectList();


$sqlNumberOfMessages = "select count(id) as how_many from table_messages";
$db->setQuery($sqlNumberOfMessages); 
$numberOfMessages = $db->loadResult();

And so on...this way you code is readable, you avoid clashing variabales name...you life is easier i think (and using different and meaningful names for variables is a best practice).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM