0

I am trying to display all entries in MySQL database table in a php page, but for some reason it is only showing the most recent. I think there are 10 entries at the moment, although there will be more.

Here is my code:

<?php 

//connect to the server
$connect = mysql_connect("localhost","...","...");

//connect to the database
mysql_select_db("blog");

//query the database
$query = mysql_query("SELECT * FROM articles");

//fetch the results / convert results into an array

WHILE($rows = mysql_fetch_array($query)):

$article_id = $rows['article_id'];
$article_title = $rows['article_title'];
$article_content = $rows['article_content'];
endwhile;

echo "$article_id $article_title<br>$article_content<br><br><br>";

?>

Does anybody have any ideas?

3 Answers 3

7

Your code is correct, however it appears you are only echoing the last item in your results. Move your echo into your WHILE loop to print out all rows. Something like:

while($rows = mysql_fetch_array($query)) {

$article_id = $rows['article_id'];
$article_title = $rows['article_title'];
$article_content = $rows['article_content'];

echo "$article_id $article_title<br>$article_content<br><br><br>";

}

Otherwise the various article variables are reset, and only the last is output. With the modifications, for each row you will get an output.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! thats sorted the problem I was having :-)
2

change this

WHILE($rows = mysql_fetch_array($query)):

$article_id = $rows['article_id'];
$article_title = $rows['article_title'];
$article_content = $rows['article_content'];
endwhile;

echo "$article_id $article_title<br>$article_content<br><br><br>";

into this

WHILE($rows = mysql_fetch_array($query))
{
$article_id = $rows['article_id'];
$article_title = $rows['article_title'];
$article_content = $rows['article_content'];

echo "$article_id $article_title<br>$article_content<br><br><br>";
}

Comments

1

You are echoing outside your WHILE loop.

Corrected:

WHILE($rows = mysql_fetch_array($query)):

$article_id = $rows['article_id'];
$article_title = $rows['article_title'];
$article_content = $rows['article_content'];
echo "$article_id $article_title<br>$article_content<br><br><br>";
endwhile;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.