未定义的索引错误(来自数据库)


Undefined Index error (from Database)

我有一个数据库,看起来像这样:

Name      | MyPrice | MyStock |
------------------------------
blue_pill |   20    | Yes     |
------------------------------
red_pill  |   10    | No      |
------------------------------

我想要一个代码,它将允许我轻松地定义4个变量(每个项目的2个价格,2个与每个项目的库存状态)。

(一般来说,我会有2个以上的项目,所以我正在寻找获得这些变量的最佳实践。)

所以我有以下代码,但它不起作用,我得到错误:

Notice: Undefined index: name(显示6次)

Notice: Undefined index: stock(显示2次)

$item1 = "blue_pill";
$item2 = "red_pill";
$productList = array();
$products = $mysqli->query("select * from table_products where Name IN ('$item1', '$item2')");
if($products){
    while($product = mysqli_fetch_assoc($products)){
        $productList[$product['name']]['MyPrice'] = $product['name']; //Errors Start Here
        $productList[$product['name']]['MyStock'] = $product['stock'];
    }
}
//first product: 
$price1 = $productList[$item1]['price']; 
$red_pill_stock = $productList[$item1]['stock'];
//second product: 
$price2 = $productList[$item2]['price'];
$blue_pill_stock = $productList[$item2]['stock'];

错误的原因是什么?

如果列的名称真的是NameMyStock,那么您的值在$product项中,正好有这样的索引-NameMyStock:

if($products){
    while($product = mysqli_fetch_assoc($products)){
        $productList[$product['name']]['MyPrice'] = $product['Name']; // Index here
        $productList[$product['name']]['MyStock'] = $product['MyStock']; // Index here
    }
}

或者,如果你不确定那里有什么钥匙,请print_r($product)并检查。