PDA

View Full Version : loop mysql query



alapimba
January 23rd, 2008, 09:56 AM
Hello
I have 2 mysql tables. lets say One table has id and name, the other has id_pic, foto, description and name_id
I have a query that join both tables and make a comparation so i can have the name and the fotos and descriptions. I did this because each person can have multiple fotos. So one table has name of the persons and the other has pictures.
My query is: $query_rs_fotos = "SELECT * FROM table 1, table 2 WHERE table 1.id = table 2.name_id";
Now i want to have the result of this query looped but i don't know how to loop it and separate the data.
Lets say i have this data:
:::.table 1:::::
id | name
1 | john
2 | bob

::::table 2:::::
id_pic | foto | description | name_id
1 | bla.jpg | bla | 1
2 | buh.jpg | buh | 2
3 | yah.jpg | yah | 1
4 | boing.jpg | boing | 1
5 | bang.jpg | bang | 2
i want the loop to return something like:
<table>
<tr><td> john</td></tr>
<tr><td> bla.jpg</td><td> yah.jpg</td></tr>
<tr><td> boing.jpg</td></tr>
<tr><td> bob</td></tr>
<tr><td> buh.jpg</td><td> bang.jpg</td></tr>
</table>
How can i do this? ???

gregmax
January 23rd, 2008, 12:05 PM
first off, your html table is all messed up :P

Try something like this (not exactly how you have it laid out, but close enough)




$res1 = mysql_query("select * from `table1`");
for($i = 0; $i < mysql_num_rows($res1); $i++) {
echo "<table>";
echo "<tr><th>" . mysql_result($res1, $i, "name") . "</th></tr>";
$res2 = mysql_query("select * from `table2` where `name_id`='" . mysql_result($res1, $i, "name_id") . "' ");
for($j = 0; $j < mysql_num_rows($res2); $j++) {
echo "<tr><td>" . mysql_result($res2, $j, "foto") . "</td></tr>";
}
echo "</table>";
}

borrob
January 24th, 2008, 06:34 AM
sql:
select a.id, b.id, a.name, b.foto from table_1 a
inner join table_2 b
on b.name_id = a.id
order by a.name, b.foto.

now execute the query

$last_name = '';
$result = // get next result ( first )
while( $result )
{
if( $last_name != $result['name'] )
{
$last_name = $result['name'];
echo "<tr><td>" . $last_name . '</td><td>' . $result['foto'] . '</td></tr>';
}
else
{
echo "<tr><td></td><td>" . $result['foto'] . '</td></tr>';
}
$result = // get next result...
}

alapimba
January 24th, 2008, 12:04 PM
$result = // get next result ( first )

is this correct?
what this variable gets?