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!

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.