Jump to content

Help outputting data from mySQL Database using PHP for a website


louiscb

Recommended Posts

I'm a beginner to PHP and am stuck as to how I can fetch data from a MYSQL database and output that information in html to the website.

Currently I get the information from the database using normal php:

$result = mysql_query("SELECT * FROM truffleProducts");

Then I assign each field from the database to a php variable in a while loop:
 

while ($row = mysql_fetch_array($result)) {
$id = $row{'id'};
$name = $row{'name'};
$price = $row{'Price_per_kg'};
$season = $row{'Season'};
$country = $row{'Country'};
$image = $row{'image'};
$review = $row{'review'};
}

Then I just print each variable in a table using simple html and php.

My problem is that it only outputs the latest element or row from my database.

I want to output the database within a HTML template so that it is professional and tidy, but i cant figure out how to do that.

Any help?

With each iteration of the loop, the variables will be overwritten. To display all the results, you could output the information within the while loop. Perhaps the following example will help:

http://www.tizag.com/mysqlTutorial/mysqlfetcharray.php

I find the easiest way is

<table>
    <?php
    while ($row = mysql_fetch_row($result)) {
        echo "<tr><td>" . join('</td><td>',$row) . "</td></tr>\n";
    }    
    ?>
</table>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.