bsavdh
bsavdh

Reputation: 13

MySQL while loop query inside other while loop query

<?php

include 'config.php';

$conn = mysql_connect("$hostname", "$username", "$password") or die ("Failed to connect to DB.");

mysql_select_db("$dbname",$conn);

    $sql="SELECT * FROM opdrachten";
    $result=mysql_query($sql,$conn);

while ($row= mysql_fetch_array($result))
{
    echo $row['name'];
    echo "<br>";
    $opdrachtid = $row["id"];

    $sql2="SELECT * FROM resultaten WHERE(opdrachtid='".$opdrachtid."')";
    $result2=mysql_query($sql2,$conn);

    while ($row2= mysql_fetch_array($result2))
    {
        echo "
                    <li>
                        <a href=\"result.php?id=".$row2["id"]."\">
                            <img src=\"".$row2["img"]." \"width=\"150\" height=\"150\">
                            <div><span>TEXT HERE</span></div>
                        </a>
                    </li>";
    }


}           
?>

What I want my code to do is (in a loop):

  1. Fetch all rows from the table 'opdrachten' and echo their 'name'.
  2. Grab the 'id' from each of the rows in 'opdrachten' > store in variable $opdrachtid
  3. Fetch rows from table 'resultaten' where 'opdrachtid == $opdrachtid' (which I just stored)
  4. Echo the 'id' and 'img' from the rows fetched from 3.

What I want to see on my page:

  1. The name of the 'opdrachten' (objective) in table 'opdrachten' with directly underneath
  2. The images (the url's of which are stored in table 'resultaten')that are assigned to these objectives (WHERE opdrachten.id = resultaten.opdrachtid)

I've looked into JOIN since that's the answer to most of the related topic's I've read here, but that doesn't seem to be what I'm looking for since I'm echo'ing in the first while and declare variables that are used for the second query.

Tables used:

'resultaten' id | opdrachtid | name

'opdrachten' id | name

Again, resultaten.opdrachtid == opdrachten.id

Thanks in advance, appreciate the help :)

Upvotes: 1

Views: 7810

Answers (2)

Mike Brant
Mike Brant

Reputation: 71384

I would certainly suggest using a JOIN here that way you can get all this data in one go. I will add one caveat however - this would take more memory that querying the database in a loop like you are currently doing, so if you have a large number of rows in either table, this might not be a suitable approach.

The query would simply be:

SELECT * FROM opdrachen
INNER JOIN resultaten ON opdrachen.id = resultaten.opdrachenid

You can then set up an array that is keyed on each id very simply like this:

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

This give you an easy way to iterate through the results, one id at a time like this:

foreach ($array as $id => $rows_for_id) {
      // output stuff for row group
      foreach ($rows_for_id as $resultaten_row) {
          // output stuff for resultaten rows
      }
}

A few other suggestions:

  • Don't use mysql_* functions as they are deprecated. Learn how to use mysqli or PDO.
  • Don't use SELECT * queries. Its is lazy and wastes bandwidth, transfer time, and system memory. Only query for the specific fields you are actually interested in. So replace the * in my example with the actual field you need.

Upvotes: 1

user2189593
user2189593

Reputation:

SELECT opdrachten.*, resultaten.* FROM opdrachten
INNER JOIN resultaten
ON resultaten.opdrachtid = opdrachten.id;

just use this as the original sql statement and iterate over it.

Upvotes: 1

Related Questions