user3235954
user3235954

Reputation: 1

Displaying mysql data in html table PHP

I have to make data from a MySQL table display in an HTML table. I've got the code to where it will display the first of seven rows from the MySQL table, but it is repeating the row nine times, instead of displaying all seven rows. What have I done wrong?

<?php
require 'database.php';

//get all product data
$query = 'SELECT * FROM products';
          $products = $db->query($query);
          $products = $products->fetch();
?>

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>SportsPro</title>
    </head>

    <body>
    <form id="Header" name="Header" method="post">
    <?php include 'header.php'; ?>
    </form>
    <form id="Content" name="Content" method="post">
    <table width="500" border="1">
    <tr>
    <th scope="col">Code</th>
    <th scope="col">Name</th>
    <th scope="col">Version</th>
    <th scope="col">Release Date</th>
    <th scope="col">&nbsp;</th>
    </tr>
    <?php foreach ($products as $product) { ?>
    <tr>
    <td><?php echo $products['productCode']; ?></td>
    <td><?php echo $products['name']; ?></td>
    <td><?php echo $products['version']; ?></td>
    <td><?php echo $products['releaseDate']; ?></td>
    <td><input type = "submit" value = "Delete" align = "right" ></td>

    </tr> 
    <?php } ?>
    </table>

    <p><a href="add_product.php">Add Product</a></p>
    </form>
    <form id="Footer" name="Footer" method="post">
    <?php include 'footer.php'; ?>
    </form>
    </body>
    </html>

Upvotes: 0

Views: 4121

Answers (2)

Osama Yawar
Osama Yawar

Reputation: 369

Why are you using $products?

FIX:

<?php 
foreach ($products as $product) {  //See *$products as $product*, so no need to use $products below instead use $product
    echo "<tr>";
    echo "<td>". $product['productCode']. "</td>";
    echo "<td>". $product['name']. "</td>";
    echo "<td>". $product['version']. "</td>";
    echo "<td>". $product['releaseDate']. "</td>";
    echo "<td><input type = \"submit\" value = \"Delete\" align = \"right\" ></td>";
    echo "</tr>" 
} 
?>

Upvotes: 2

Ramesh
Ramesh

Reputation: 4283

You have to replace,

$products = $products->fetch(); 

with

$products = $products->fetchAll();

Inside td tags, you have,

<?php echo $products['productCode']; ?>

Change it to like below for all lines,

<?php echo $product['productCode']; ?>

Upvotes: 1

Related Questions