views:

43

answers:

1

Is it possible to use 1 query instead 2? Or this way is better? (for speed)

<?
$q1 = mysql_query("SELECT name,url,id FROM gallery") or die(mysql_error());

if (mysql_num_rows($q1) > 0) {
  while ($row = mysql_fetch_array($q1)) {   
    echo 'IMAGES FROM '.$row['name'];
    $id = $row['id'];
    //second query for each gallery
    $imgq = mysql_query("SELECT img  FROM img WHERE ids=" . $id . " ") or die(mysql_error());
    while ($img = mysql_fetch_array($imgq)) {
      ?><img src="<?=$img['img'];?>"><?
    } //multiple images
  }
}
+4  A: 

You need a Join to bring this back in one query.

SELECT name,url,id,img
FROM gallery g
JOIN img i ON i.ids=g.id

This is more efficient as it reduces the number of requests and table accesses you are making.

It does mean that you will be bringing back repeated rows with name,url,id but the effect of this will likely be minimal.

Martin Smith
That's not quite right, it should probably be `i.ids=g.id`
Borealid
@Borealid - Already fixed!
Martin Smith