PHP problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
RossDolan
Forum Commoner
Posts: 31
Joined: Tue Jul 19, 2011 5:44 am

PHP problem

Post by RossDolan »

I am trying to get this php script to go to my database gather all the data from my news table and display it in a table, however it only displays the most recent record and I cannot figure out why, I might be making a stupid mistake but cannot see anything wrong with it, any suggestions would be appreciated. Cheers.

Code: Select all

<?php
include 'dbconnect.php';

$newsquery = mysql_query('SELECT * FROM news');
if (!$newsquery)
{
	die ('<p> Error performing query: ' .mysql_error() . '</p>');
}

while($nq = mysql_fetch_array($newsquery))
{
	$newsid = $nq['ID'];
	$newsdate = $nq['date'];
	$newstext = $nq['news'];
}
?>

<table border = "1">

<tr><th>ID</th><th>Date</th><th>News</th></tr>
<?php 
echo ("<td>$newsid</td>\n");
echo ("<td>$newsdate</td>\n");
echo ("<td>$newstext</td>\n");
?>
</tr>
</table>
User avatar
Bill H
DevNet Resident
Posts: 1136
Joined: Sat Jun 01, 2002 10:16 am
Location: San Diego CA
Contact:

Re: PHP problem

Post by Bill H »

Your html display is outside the "while" loop, so it is executed only after the loop has completed. That's why only the most recent item is displayed. It needs to be within the loop so that each item is displayed before the next item is extracted from the result set.

Code: Select all

<table border = "1">

<tr><th>ID</th><th>Date</th><th>News</th></tr>

<?php
include 'dbconnect.php';

$newsquery = mysql_query('SELECT * FROM news');
if (!$newsquery)
{
        die ('<p> Error performing query: ' .mysql_error() . '</p>');
}
while($nq = mysql_fetch_array($newsquery))
{
        $newsid = $nq['ID'];
        $newsdate = $nq['date'];
        $newstext = $nq['news'];

         echo ("<tr>\n<td>$newsid</td>\n");
         echo ("<td>$newsdate</td>\n");
         echo ("<td>$newstext</td>\n</tr>\n");
}
?>

</table>
This really should have been in the "PHP Code" questions forun, though, not in this one.
RossDolan
Forum Commoner
Posts: 31
Joined: Tue Jul 19, 2011 5:44 am

Re: PHP problem

Post by RossDolan »

Thanks a lot mate, got it working, I'll be sure to use that forum next time, still getting used to the site lol, cheers
Post Reply