PHP致命错误:无法在file.php中使用mysqli_result类型的对象作为数组

时间:2013-12-05 23:28:59

标签: php mysql mysqli

我有以下代码:

$productQuery     = "SELECT ean, name FROM products WHERE category = '$category'";
$productResult    = $mysqli->query($productQuery);

while ($productRow = $productResult->fetch_assoc()) {
    $productPriceQuery     = "SELECT ean, price+shipmentCost AS totalPrice FROM prices WHERE ean = $productRow[ean] ORDER BY totalPrice ASC";
    $productPriceResult    = $mysqli->query($productPriceQuery);

    $totalPrice            = $productPriceResult->fetch_assoc();

    echo $productPriceResult["productURL"];
}

但是我收到了回音线的以下错误:

PHP Fatal error:  Cannot use object of type mysqli_result as array in file.php

我已经阅读了本网站和其他网站上的一些文章,但是我不理解这个问题,也无法自己解决。

2 个答案:

答案 0 :(得分:-1)

$productPriceResult是一个结果,而不是一个获取的数组。

似乎“productURL”应该存储在products表中,但为了便于解释,我将保留它的方式:在prices表中。

您需要在SELECT语句中添加“productURL”,如下所示:

SELECT ean, productURL, price+shipmentCost AS totalPrice FROM prices ...

并像这样访问“productURL”:

$totalPrice['productURL'];

顺便提一下,价格会像这样访问:

$totalPrice['totalPrice'];

我建议将$totalPrice变量重命名为$priceData或更合适。

编辑:

以下是如何循环查看价格数据的示例 为了便于阅读,我截断了实际的查询字符串。

// loop through rows fetched from "products" table
while ($productRow = $productResult->fetch_assoc()) {

    // query price data for this product
    $productPriceQuery     = "SELECT ean, productURL, etc...";
    $productPriceResult    = $mysqli->query($productPriceQuery);

    // loop through rows fetched from "prices" table
    while ($priceData = $productPriceResult->fetch_assoc()) {
      echo "<p>".$priceData['productURL']."</p>";
    }

}

答案 1 :(得分:-2)

尝试使用

public function DisplayProducts() {
    $productQuery     = "SELECT ean, name FROM products WHERE category = '$category'";
    $productResult    = $this->mysqli->query($productQuery);

    while ($productRow = $productResult->fetch_object()) {
        $productPriceQuery     = "SELECT ean, price+shipmentCost AS totalPrice FROM prices WHERE ean = $productRow->ean ORDER BY totalPrice ASC";
        $productPriceResult = $this->mysqli->query($productPriceQuery);

        while($row=$productPriceResult->fetch_object()) {
        $ProductPrice = $row->totalPrice;
        $ProductURL = $row->productURL; //I'm not seeing where you're querying for the URL so you'll have to append accordingly.
            }
    }

然后创建你正在谈论的桌子。

   echo "<table><th>Product Price</th><th>Product URL</th>";
    echo "<tr><td>" . $ProductPrice . "</td><td>" . $ProductURL . "</td></tr>";
    echo "</table>";
}

希望从那里开始有一些帮助。祝你好运。