Jump to content

Help outputting data from mySQL Database using PHP for a website


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?

Edited by louiscb

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>
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.