0

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>
1
  • Check the result of var_dump($products); Commented Feb 23, 2014 at 7:00

2 Answers 2

2

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>" 
} 
?>
Sign up to request clarification or add additional context in comments.

Comments

1

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']; ?>

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.