how to decrease queries in php/mysql array selection loop
Posted
by Mac Taylor
on Stack Overflow
See other posts from Stack Overflow
or by Mac Taylor
Published on 2010-05-26T14:02:34Z
Indexed on
2010/05/26
15:01 UTC
Read the original article
Hit count: 208
hey guys
i need to show stories details and tags' names in my php/mysql project .
for every story row, there is a filed named : tags that save tags id as an array
Table name: stories
table filed : tags
example of tags filed :
1 5 6 space between them
and i have a tag table that looks like this
Table name : bt_tags
Table fileds : tid,tag
now problem :
when using while loop to fetch all fields in story table , the page uses 1 query to show every stories' detail but for showing tag's names , i should query another table to find names , we have ids stored in story table
now i used for loop between while loop to show tag names but im sure there is a better way to decrease page queries
$result = $db->sql_query("SELECT * FROM ".STORY_TABLE." ");
while ($row = $db->sql_fetchrow($result)) {
//fetching other $vars ----
$tags_id = explode(" ",$row['tags']);
$c = count($tags_id);
for($i=1;$i<$c-1;$i++){
list($tag_name,$slug) =
$db->sql_fetchrow($db->sql_query(
'SELECT `tag`,`slug` FROM `bt_tags` WHERE `tid` = "'.tags_id[$i].'" LIMIT 1'
));
$sow_tags = '$tag_name,';
}
im not allowed to change anything in database table
how can i improve this script and show tag's names without using *for loop ?*
© Stack Overflow or respective owner