问题描述:

I need to pull 3 values from a table and assign each one to a variable

each value is based on to columns, a type and an id

$ht_live_query = mysql_query("SELECT htcode FROM coupon WHERE pid='$pid' AND type='L'");

$ht_live_result = mysql_fetch_array($ht_live_query);

$htCODE_Live = $ht_live_result['htcode'];

You can see that I am assigning the desired value to the variable $htL

$ht_General_query = mysql_query("SELECT htcode FROM coupon WHERE pid='$pid' AND type='G'");

$ht_General_result = mysql_fetch_array($ht_General_query);

$htCODE_General = $ht_General_result['htcode'];

$ht_Reward_query = mysql_query("SELECT htcode FROM coupon WHERE pid='$pid' AND type='R'");

$ht_Reward_result = mysql_fetch_array($ht_Reward_query);

$htCODE_Reward = $ht_Reward_result ['htcode'];

I know I am doing this the hard way but can not figure out how to do the foreach or while loop to attain the desired results.

网友答案:

Use an IN() clause as IN('L','G','R').

$htrrquery = mysql_query("SELECT htcode, type FROM coupon WHERE pid='$pid' AND type IN('L','G','R')");

When fetching results, you can check the value and do something different if necessary.

while ($row = mysql_fecth_array($htrrquery)) {
  echo = $row['htcode'];
  switch ($row['type']) {
    case 'L': $htL = $row['htcode']; break;
    case 'G': $htG = $row['htcode']; break;
    case 'R': $htR = $row['htcode']; break;
  }
}
网友答案:
$htlquery = mysql_query("SELECT htcode FROM coupon WHERE pid='$pid' 
                         AND type IN 'G','L','R') ORDER BY type");
while($row=mysql_fetch_array($htlquery)) {  // EDIT: added loop
    $return[] = $row[0];
}

list($htG, $htL, $htR)  = $return;
相关阅读:
Top