I have a database that looks like this:
Name | WebsitePrice | WebsiteStock |
-----------------------------------------
football | 20 | Yes |
-----------------------------------------
basketball | 10 | No |
-----------------------------------------
hockey | 30 | Yes |
-----------------------------------------
I want to create 2 variables for each item:
- price of item
- stock of item.
This is the shortest way I came up with:
$item1 = "football";
$item2 = "basketball";
$item3 = "tennis-ball";
$productList = array();
$products = $mysqli->query("select * from table_products where Name IN ('$item1', '$item2', '$item3')");
if($products){
while($product = mysqli_fetch_assoc($products)){
$productList[$product['Name']]['WebsitePrice'] = $product['WebsitePrice'];
$productList[$product['Name']]['WebsiteStock'] = $product['WebsiteStock'];
}
}
//first product:
$price1 = $productList[$item1]['WebsitePrice'];
$stock1 = $productList[$item1]['WebsiteStock'];
//second product:
$price2 = $productList[$item2]['WebsitePrice'];
$stock2 = $productList[$item2]['WebsiteStock'];
//third product:
$price3 = $productList[$item3]['WebsitePrice'];
$stock3 = $productList[$item3]['WebsiteStock'];
It looks pretty messy to me. Is there any better way to do this? especially if we assume that I might have 20 items and not just 3.
for example, is there a way to skip writing the whole ('$item1', '$item2', '$item3')
line and make that line refer to number of items that are defined in the first code block?