必须有一种更简单的方法..从mysql中提取数据

时间:2011-11-13 01:35:32

标签: php mysql foreach while-loop

我需要从表中提取3个值并将每个值分配给变量 每个值都基于列,类型和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'];
  

您可以看到我正在为变量$ 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'];

我知道我正在努力做到这一点,但无法弄清楚如何做foreach或while循环以达到预期的效果。

2 个答案:

答案 0 :(得分:3)

IN()子句用作IN('L','G','R')

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

获取结果时,您可以检查值并在必要时执行不同的操作。

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;
  }
}

答案 1 :(得分:0)

$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;