使用php数组查询数据库

问题描述 投票:-3回答:1

我试图使用数组中传递的值来查询mysql数据库。问题是第一个元素产生两个结果。这是我的代码和结果。

$common = array_intersect($ingredients, $ingredients2);
unset($common['1']);
$unique = array_unique($common);
echo "The common array is:";
print_r(array_count_values($common));
echo "<br> The unique array is :";
print_r($unique);
echo "<br>";
echo extract($unique)."<br>";
$i = 0;
$sum = 0;

foreach (array_count_values($common) as $key => $value) {
    $keys = "$key";
    $value = "$value";
    echo "$keys : ";
    echo "$value<br>";
    $i++;
    $sql = mysql_query("SELECT * FROM `ingredients` WHERE `name`  = '$keys'") or die(mysql_error());
    while ($row = mysql_fetch_array($sql)) {

        $price = $row['price'];
        echo "The price is : $price<br>";
        $total_price = $value*$price;
        echo "The total price for $keys is : $total_price<br>";
         $sum+= $total_price;
    }
}
echo "The sum of the prices is $sum";

这是我得到的:

The common array is:Array ( [test] => 3 [ugali] => 2 [mboga] => 2 [0] => 1 )

The unique array is :Array ( [0] => test [2] => ugali [4] => mboga [8] => 0 )
0
test : 3
The price is : 100

The total price for test is : 300

The price is : 100

The total price for test is : 300

ugali : 2

The price is : 100

The total price for ugali is : 200

mboga : 2

The price is : 4

The total price for mboga is : 8

0 : 1

The sum of the prices is 808
php arrays foreach while-loop
1个回答
0
投票

我得到了答案。我删除了while循环,而不是

while ($row = mysql_fetch_array($sql)) {}

我有

$row = mysql_fetch_array($sql);

这解决了这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.