beam
beam

Reputation: 1

One query instead of multiple queries

I'm currently running multiple mysql queries but want to just run one and loop through it. How can I improve this?

 $query = mysql_query("SELECT productid, code, size, quantity, sizechart, rprice, price, weight FROM inventory WHERE code = '$productcode1'"); 
 while ($rows1 = mysql_fetch_array($query)) 
 { 
     $productids1 = $rows1['productid']; 
     $codes1 = $rows1['code']; 
     $sizes1 = ucwords($rows1['size']); 
     $quantitys1 = $rows1['quantity']; 
     $sizechart = $rows1['sizechart']; 
     $rprice = $rows1['rprice']; 
     $sprice = $rows1['price']; 
     $dweight = $rows1['weight']; 
 } 

Each query then carries on the same but $productcode2 and $productcode3 etc.

Upvotes: 0

Views: 123

Answers (3)

nnevala
nnevala

Reputation: 5997

One solution would be using PDO's prepared statements.

Quick, untested and dirty example based on PHP reference:

$stmt = $dbh->prepare("SELECT productid, code, size, quantity, sizechart, rprice, price, weight FROM inventory WHERE code = :code");
$stmt->bindParam(':code', $code);

foreach ($productCodes as $code) {
  $stmt->execute();
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  // Do something with the results
}

Upvotes: 1

bswietochowski
bswietochowski

Reputation: 15

Change "Where code = '$prouctcode1'" on "where code IN (...)"

Upvotes: 1

Jamie Treworgy
Jamie Treworgy

Reputation: 24334

... WHERE code IN ('$productcode1','$productcode2',...)

Upvotes: 6

Related Questions