Jump to content

Retrieving sql query values and store them into array


CSkovholm

Recommended Posts

Hey guys, i've got a question.

 

I have a SQl string that goes: "SELECT * FROM products WHERE id IN(20,3,1)"

 

the 3 ids that are shown in the query, represents the product ids for a shopping system. I now have a sql query that retrieves the information about the products.

 

I want to create an array containing the requested values, from the sql query, and then store the array into a variable. Something like this:

 

<?php

require "db.php"; //Db connection

$sql = "SELECT * FROM products WHERE id IN (20,3,1)"; //Sql 
$q = mysql_query($sql); //Query
$rows = mysql_fetch_assoc($q); //Returned rows

$total_price = implode(+, $rows['price']);
echo $total_price

?>

 

I know that's not it.. But how is this done?

Thanks in advantage!

How are you wanting it to be displayed?

 

If you're wanting to display the 3 results of Price from the 3 id's given.. try this out.

<?php
require "db.php";

$sql = "SELECT * FROM products WHERE id IN (20,3,1)";
$q = mysql_query($sql);
while($rows = mysql_fetch_assoc($q)) {
    $price[] = $rows['price'];
}

$total_price = implode('+', $price);
echo $total_price;
?>

 

I'm not sure if that does what you are wanting it to do though. It might bring out a string rather than an answer.

Inside the loop, just add to a $total counter:

<?php
require "db.php";

$sql = "SELECT * FROM products WHERE id IN (20,3,1)";
$q = mysql_query($sql);
$total = 0; //Total of the addition
while($rows = mysql_fetch_assoc($q)) {
    $price[] = $rows['price'];
    $total += $rows['price']; //Add to the total
}

$total_price = implode('+', $price);
echo $total_price . ' = ' . $total;
?>

 

Alternatively you could just use array_sum:

<?php
require "db.php";

$sql = "SELECT * FROM products WHERE id IN (20,3,1)";
$q = mysql_query($sql);
while($rows = mysql_fetch_assoc($q)) {
    $price[] = $rows['price'];
}

$total_price = implode('+', $price);
echo $total_price, ' = ', array_sum($price);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.