how to get value in array from individual query
i have a
Book ID Array
Array
(
[0] => 61
[1] => 72
[2] => 78
[3] => 100
[4] => 102
)
now from another table table_bookPrice
where price filed is given
i want that select all price from table_bookPrice where book id is in given array (book ID Array) and if price is not mentioned in table_bookPrice
field then it would be automatic 500
what will be exac开发者_StackOverflowt query
so the array i got is like this
Book Price Array
Array
(
[0] => 150
[1] => 100
[2] => 500 ( not mentioned in table, so it is 500)
[3] => 300
[4] => 200
)
I am at work so could not test or compile it, but I hope my logic is understandable.
Not sure if this will work but something along these lines
$book_price_array = array(); //contents to be added.
// loop through the array an examine its price by querying your table.
foreach ($book_id_array as $key => $value) {
$price = mysql_query("SELECT price FROM table_bookPrice
WHERE book_id = {$value}");
// there is a price, set the price.
if ($price > 0 && $price != NULL) $book_price_array[$key] = $price;
// there is no price, set the default price
else $book_price_array[$key] = 500;
}
Here's the test database I built for your problem:
mysql> select * from table_bookPrice;
+----+-------+--------+
| id | price | bookid |
+----+-------+--------+
| 1 | 150 | 61 |
| 2 | 100 | 72 |
| 3 | 300 | 100 |
| 4 | 200 | 102 |
+----+-------+--------+
4 rows in set (0.00 sec)
Here's the PHP code:
<?php
$books=array(61,72,78,100,102);
// establish an assoc array of bookid => default_price
$prices=array();
foreach($books as $bookid){
$prices["$bookid"]=500;
}
// build query to select all prices stored in database
$bookids=implode(', ',$books);
mysql_connect('localhost','aj','nothing') or die('unable to connect!');
mysql_select_db('books') or die('unable to select db!');
$stmt="SELECT bp.bookid, bp.price FROM table_bookPrice bp WHERE bp.bookid IN ($bookids)";
$res=mysql_query($stmt);
while( ($rec= mysql_fetch_assoc($res)) ){
$idstr=(string)$rec['bookid'];
$prices[$idstr]=$rec['price'];
}
print_r($prices);
?>
This outputs:
Array
(
[61] => 150
[72] => 100
[78] => 500
[100] => 300
[102] => 200
)
精彩评论