Database info display troubles

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
aolle34
Forum Newbie
Posts: 4
Joined: Mon Dec 16, 2013 10:13 am

Database info display troubles

Post by aolle34 »

Code: Select all

$products
is a table in my database and I'm trying to display a list of them on the target page. Here's my code:

Code: Select all

<?php include 'header.php'; ?>
<div id="main">
<div id="content">
    <ul class="nav">
        <?php foreach ($products as $product) : ?>
        <li>
            <a href="?action=view_product&product_id=
                <?php echo $product['product_id']; ?>">
                <?php echo $product['name']; ?>
            </a>
        </li>
        <?php endforeach; ?>
    </ul>
</div>
</div>
<?php include 'footer.php'; ?>
And my get_products() from another file:

Code: Select all

function get_products() {
global $conn;
$query = 'SELECT * FROM products
          ORDER BY product_id';
$products = $conn->query($query);
return $products;
}

function get_product($product_id) {
global $conn;
$query = "SELECT * FROM products
          WHERE productID = '$product_id'";
$product = $conn->query($query);
$product = $product->fetch();
return $product;
}
It's telling me that

Code: Select all

$products
is an undefined variable. I have no idea why. :banghead:
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Database info display troubles

Post by Celauran »

Code: Select all

<?php include 'header.php'; ?>
<div id="main">
<div id="content">
    <ul class="nav">
        <?php foreach ($products as $product) : ?>
        <li>
            <a href="?action=view_product&product_id=
                <?php echo $product['product_id']; ?>">
                <?php echo $product['name']; ?>
            </a>
        </li>
        <?php endforeach; ?>
    </ul>
</div>
</div>
<?php include 'footer.php'; ?>
I don't see it defined anywhere in there.
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Database info display troubles

Post by twinedev »

Without being able to see all of the code, I would suggest back tracing through the code and do do var_dumps in the code from this section back to where you loaded the data to see where you "loose it". It could be as simple as what actually calls this code is a function, and $products isn't in scope for it.

On a different topic, you will probably want to watch this code:

Code: Select all

            <a href="?action=view_product&product_id=
                <?php echo $product['product_id']; ?>">
As line breaks will probably be carried over to the source code, thus breaking the actual links.
Post Reply