/    Sign up×
Community /Pin to ProfileBookmark

Displaying mysql tables in php

Hi there,

I have 2 tables related on a one to many basis. I want to display the data when called as follows:

Table 1 Entry 1:
Table 2 Related Entry 1
Table 2 Related Entry 2
Table 1 Entry 2:
Table 2 Related Entry 1
etc
etc

However at the moment all i can get it to display is:

Table 1 Entry 1:
Table 2 Related Entry 1
Table 1 Entry 1:
Table 2 Related Entry 2
Table 1 Entry 2:
Table 2 Related Entry 1
etc
etc

So its repeating the header data from the 1st table instead of simply writing it once then including all the related data from table 2.

I just wondered if anyone could suggest how i could get round this. My original sql uses a WHERE clause and i was thinking it might be possible with a JOIN, but im not sure how to use these?

Cheers

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogFeb 08.2005 — I think you could do something like this (untested):
[code=php]
<?php
$query = "SELECT t1.col1, t2.col2 FROM table1 AS t1 LEFT JOIN table2 AS t2 ON t1.col1=t2.col1";
$result = mysql_query($query);
$col1 = "";
$firstRow = TRUE;
echo "<ul>n";
while($row = mysql_fetch_array($result))
{
if($row[0] != $col1) # it's a new t1.col1, so make it first-leve list
{
$col1 = $row[0];
if(!$firstRow)
{
echo "</ul>n";
}
else # first entry output, so turn off flag and don't need to close ul
{
$firstRow = FALSE;
}
echo "<li>{$row[0]}</li>n<ul>n"; # print t1.col1 and start sub-list
}
echo "<li>{$row[1]}</li>n"; # print t2.col2 as part of 2nd level ul
}
echo "</ul>n</ul>n"; # close up all both levels of ul
?>
[/code]
×

Success!

Help @htmlperlman spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...