简体   繁体   English

为什么会出现此错误,所以一切看起来都正确:“未定义索引”?

[英]Why am I getting this error, everything looks right: “Undefined index”?

I am at a loss here. 我在这里茫然。 I cannot for the life of me figure out why I am getting the error. 我一生无法弄清为什么我得到了错误。

Notice: Undefined index: price in /home/*****/public_html/newfinal/home_view.php on line 14

Notice: Undefined index: description in /home/****/public_html/newfinal/home_view.php on line 15

Here are the relevant code snippets: 以下是相关的代码段:

PHP/ SQL PHP / SQL

function get_product($product_id) {
    global $db;
    $query = "SELECT * FROM prjProducts p"
            . " INNER JOIN prjCategories c"
            . " ON p.categoryID = c.categoryID"
            . " WHERE productID = :product_id";
    try {
        $stmt = $db->prepare($query);
        $stmt->bindValue(':product_id', $product_id);
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $stmt->execute();
        $result = $stmt->fetchAll();
        $stmt->closeCursor();
        return $result;
    } catch (PDOException $ex) {
        $error = $ex->getMessage();
        echo $error;
    }
}

PHP PHP

// Set the featured product Id's in an array
$product_ids = array(3, 5, 10);

// Get an array of featured producst from the database
$products = array();
foreach ($product_ids as $product_id) {
    $product = get_product($product_id);
    $products[] = $product; // add the product to the array

}

HTML HTML

<?php foreach ($products as $product) :
          // Get product data
          $price = $product['price'];
          $description = $product['description'];

I have been banging my head at this one for a couple of hours now. 我已经在这头上撞了几个小时了。 I've tried to echo the arrays, and I can print out the arrays without issue. 我尝试回显数组,并且可以打印出数组而不会出现问题。 I'm sure it is some small formatting error that I am missing somewhere. 我确定这是我在某处缺少的一些小的格式化错误。

  1. First check whether you have the price and description columns in your table prjProducts . 首先检查表prjProducts是否有pricedescription列。

  2. In your foreach ($products as $product) loop, do a var_dump for $product and check to see whether it is an array or an object ? 在您的foreach ($products as $product)循环中,对$product进行var_dump并检查其是否为arrayobject

If it is not an array you should do $product->price instead of $product['price'] . 如果不是数组,则应该执行$product->price而不是$product['price']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM