我有一个如下所示的数据库:
Name | MyPrice | MyStock |
------------------------------
blue_pill | 20 | Yes |
------------------------------
red_pill | 10 | No |
------------------------------
我想要一个可以轻松定义 4 个变量的代码(2 个是每件商品的价格,2 个是每件商品的库存状态)。
(一般来说,我的项目会多于 2 个,因此我正在寻找获取这些变量的最佳实践。)
所以我有以下代码,但它不起作用,我收到错误:
注意:未定义索引:名称
(显示6次)
注意:未定义索引:股票
(显示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'];
是什么导致了这个错误?
最佳答案
如果您的列名称确实是 Name
和 MyStock
,那么您的值位于 $product
项中,并且完全正确 此类索引 - Name
和 MyStock
:
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)
并检查。
关于php - 未定义索引错误(来自数据库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34582378/