Page 1 of 1

PHP problem

Posted: Fri Nov 04, 2011 9:49 am
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>

Re: PHP problem

Posted: Fri Nov 04, 2011 10:24 am
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.

Re: PHP problem

Posted: Fri Nov 04, 2011 11:47 am
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