使用php数组查询数据库
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用php数组查询数据库相关的知识,希望对你有一定的参考价值。
我试图使用数组中传递的值来查询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
答案
我得到了答案。我删除了while循环,而不是
while ($row = mysql_fetch_array($sql)) {}
我有
$row = mysql_fetch_array($sql);
这解决了这个问题。
以上是关于使用php数组查询数据库的主要内容,如果未能解决你的问题,请参考以下文章