here is my array
Array
(
[0] => 31
[1] => 36
[2] => 41
)
the 31,36, and 41 are id's of a record. the elements in this array can be from anywhere of 1 element to 10+ elements. the table structure looks something like this (shortened-version)
tbl_cart
---------
id (auto-incremented)
product_name
price
what i'm trying to figure out is how can i do a query that will grab the id's listen in a dynamically created array then accumulate the price for each respected id and display the output?
thanks, let me know if this doesnt make sense.
You can get the ids as a comma-separated string using the implode()
function, like this :
$str_ids = implode(', ', $array);
Then, you can inject that into an SQL query, using in()
:
select sum(price) as total_price
from tbl_cart
where id in ($str_ids)
you want to sum the prices for the ids in your list right?
$idStr = implode(',', $arr);
$sql = "SELECT sum(price) FROM tbl_cart WHERE id in ($idStr)";
$vars = array(1, 2, 3, 4);
$newvars = array();
foreach($vars as $var){
if(!empty($var))
$newvars[] = " ID = ".$var;
}
$where = join(" OR ", $newvars);
$sql = "SELECT * FROM table ".(($where)?"WHERE ".$where: null);
echo $sql;
$ids = implode(',', $array);
$query = "SELECT id, price FROM tbl_cart WHERE id in ($ids)";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "ID: {$row['id']} Price: {$row['price']}");
}
Outputs
// ID: 31 Price: (the price)
// ID: 36 Price: (the price)
// ID: 41 Price: (the price)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.