PHP rework my code:

Associate
Joined
31 May 2005
Posts
2,180
Location
Alfreton,Derbyshire
I have two tables in the database, one for weblog entries and one for comments;

I have written the following code but think that this is possibly the wrong way to go about it? This is just me testing at the moment, but would like some advice

$query = "SELECT * FROM entry";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
$entry_id = $row['entry_id'];
$entry = $row['content'];
$author = $row['author'];
echo "<h4>$author wrote the following weblog entry:</h4><p>$entry</p>";
$sub_query = "SELECT * FROM comments WHERE entry_id = '$entry_id'";
$result2 = mysql_query($sub_query);
while ($row2 = mysql_fetch_assoc($result2))
{
$comment = $row2['content'];
$author2 = $row2['author'];
$email = $row2['email'];
echo "<br>$author2 / $email left the following comment:<br><p>$comment</p>";
}



}

Should i be putting a seperate query within the while loop? is that bad practice? Or is the way im going just stupid...A little direction thanks...

Oh, please ignore variable names, like i say proof of concept really
 
n30_mkii said:
Should i be putting a seperate query within the while loop? is that bad practice? Or is the way im going just stupid...A little direction thanks...
Don't quite know what you're getting at here. Are the 'comments' being submitted by site visitors?
Your code looks fine. I, personally would have laid it out like this:
Code:
$query = "SELECT * FROM entry";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
do {
$entry_id = $row['entry_id'];
$entry = $row['content'];
$author = $row['author'];
echo "<h4>$author wrote the following weblog entry:</h4><p>$entry</p>";
$sub_query = "SELECT * FROM comments WHERE entry_id = '$entry_id'";
$result2 = mysql_query($sub_query);
$row2 = mysql_fetch_assoc($result2);
do {
$comment = $row2['content'];
$author2 = $row2['author'];
$email = $row2['email'];
echo "<br>$author2 / $email left the following comment:<br><p>$comment</p>";
} while ($row2 = mysql_fetch_assoc($result2));
} while ($row = mysql_fetch_assoc($result));
I'm sure some of the more experienced PHP programmers on the forum will pop in to submit more ideas ;)

HTH
 
Thanks for that, yes other people will leave the comments, which will go to a seperate table flgged against the entry_id.

Anyone else have ideas?
 
Looks fine to me, and contrary to Freakish_05's preferred use of do..while loops I'd prefer to do it with the standard while loop like you have done, since in the event that there are no rows in the database the code will automatically not be processed. In Freakish_05's code, he will have to put in some extra handling that is currently not in his example.

Looks ok though :)
 
Back
Top Bottom