1

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.

4 Answers 4

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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)";

Comments

0
$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;

Comments

0
$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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.