Reputation: 13
<?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):
What I want to see on my page:
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
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:
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
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