Hi there everyone,
I'm trying very hard to leave the comfort of the very basics and journey into more efficient coding. Usually, I'm able to find the necessary methods by googling, but I'm not having much luck with this particular problem. Here's my example.
I'm listing classified ads that a user owns on a profile page. During the database query, I'm pulling all records that matches their user_id. Once I've got that, I perform another query to get the category title for the present record in the loop and in the very same loop, I do a third query to get the title of the parent category for the category that the ad is under. Here's what it ends up looking like:
$query1="SELECT id,cat_id,title,DATE_format(create_date, '%b %e, %Y, %l:%i%p') as create_date,DATE_format(start_date, '%b %e, %Y, %l:%i%p') as start_date,life_span FROM classifieds_ads WHERE user_id=$user_id";
$result1=mysql_query($query1) or die (mysql_error());
while($row=mysql_fetch_array($result3)){
$id=$row['id'];
$cat_id=$row['cat_id'];
$title=$row['title'];
$create_date=$row['create_date'];
$start_date=$row['start_date'];
$life_span=$row['life_span'];
$query2="SELECT title,parent FROM classifieds_categories WHERE cat_id=$cat_id";
$result2=mysql_query($query2) or die (mysql_error());
while($row=mysql_fetch_array($result2)){
$title=$row['title'];
$parent=$row['parent'];
$query3="SELECT title FROM classifieds_categories WHERE cat_id=$parent";
$result3=mysql_query($query3) or die (mysql_error());
while($row=mysql_fetch_array($result3)){
$parent=$row['parent'];
}
}
echo("
<a href='link.php?id=".$id.">".$title."</a> Created: ".$create_date." in Category: ".$parent_title."~>".$title." <br />
");
}
Which leads me to my question; Is there a better way to handle this? All of these nested loops are making me quite dizzy and it seems wasteful to keep pasting the same code over and over. For the life of me, however, I can't find anything through my searches, likely because I don't know what to search for.
Any thoughts on the matter would be greatly appreciated.
thanks,
json