简体   繁体   中英

PHP - Too many mysql_query(“SELECT .. ”) ..?

Hey, I'm making an e-shop and to display the tree of categories and all the products with their multiple variations of prices I made like more than 150 mysql_query("SELECT ..."); queries on one page. (If I count the "while" loops).

Is it too many, and if yes, can it have any negative effect? (ofc. it takes longer to load the data ..)

Also can I anyhow achieve the effect of this code without doing it that way?

$result2 = mysql_query("SELECT * FROM ceny WHERE produkt_id='$id' ORDER BY gramaz");
$result3 = mysql_query("SELECT * FROM ceny WHERE produkt_id='$id' ORDER BY gramaz");
$result4 = mysql_query("SELECT * FROM ceny WHERE produkt_id='$id' ORDER BY gramaz");
$result5 = mysql_query("SELECT * FROM ceny WHERE produkt_id='$id' ORDER BY gramaz");

while( $row2 = mysql_fetch_array( $result2 )) { }
while( $row3 = mysql_fetch_array( $result2 )) { }
while( $row4 = mysql_fetch_array( $result2 )) { }
while( $row5 = mysql_fetch_array( $result2 )) { }

Thanks, Mike.

It's usually a good idea to reduce the number of queries you run. In this case you can select rows for all products in a single query, for example:

SELECT * FROM ceny WHERE produkt_id IN (?, ?, ?, ...) ORDER BY gramaz

Then you will have a single loop that iterates over the results and populates the appropriate variable(s):

$ceny = array()
while ($row = mysql_fetch_array($result)) {
    $id = $row['produkt_id'];
    $ceny[$id][] = $row;
}

Now $ceny[$produkt_id] contains a list of rows from ceny for that product, sorted by gramaz .

It seems your situation is in desperate need of a join, and possibly some AJAX if you really want to cut down on the load for that page.

If I'm understanding you correctly, you want to display a tree menu of categories, and presumably when you click to open a particular branch, you see the items which fall under that category, correct?

So, your current approach is to loop through the categories, then do a select * from the items table to show them, right?

If this is the case, and I'm understanding it correctly, this could be solved using a simple join. You would want to do a single select statement to the items table, join to the categories table by the foreign key you have in the items table, then sort by the category.

Now, you'd be able to loop through the single result set to show both the categories and the associated items.

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