I have code:
$somevar=mysql_query("SELECT * FROM feed");
while ($fetched=mysql_fetch_array($somevar)) {
$nextvar=mysql_query("SELECT FROM comments WHERE feed_id='".$fetched['id']."'");
while ($anotherfetch=mysql_fetch_array($nextvar)) {
echo $anotherfetch['comment'];
}
echo $fetched['person'].$fetched['text'];
}
Tables structures:
feed
id | person | text
comments
id | feed_id | person | comment
What’s the best solution to optimize it and is it possible at all? I know it’s a big mistake to make while in while but it looks like there is no other way..
A
whilewithin awhileis not so much the issue as is nested queries. This is often an indication of an N + 1 problem.While there are different solutions, my suggestion in your case would be to use a
JOINand stitch the data together as you need it.Also, as noted in the comments, please don’t use the
mysql_*functions as they are in the deprecation process. Use MySQLi or PDO instead and be a better PHP Developer.