来自sql查询的php质量变量

时间:2012-01-12 00:19:52

标签: php sql variables

我的PHP脚本的这一部分循环遍历记录集并将数据存储到变量中。

 $sql_result5 = mysql_query("SELECT * FROM turfs WHERE city = '$city'", $db); $query++;
 while ($rs5 = mysql_fetch_array($sql_result5)) { 
    if ($rs5[plot] != "") {
       ${$rs5[plot].'_exist'} = 1; 
       ${'$p_color_'.$rs5[plot]} = $rs5[color]; 
       ${$rs5[plot].'_1'} = $rs5[color1]; 
       }
    }

然后我使用这些数据来填充20x20网格,这样循环将通过400条记录存储每个数据,并且对于每条记录(网格中的框),需要大约5个左右的变量。

创建这么多变量是不是一个坏主意?有一个更好的方法吗?也许是阵列?

2 个答案:

答案 0 :(得分:3)

正如您所做的那样,创建变量并不是最好的方法。相反,要么使用array,要么在while循环中创建网格。

创建数组

$sql_result5 = mysql_query("SELECT * FROM turfs WHERE city = '$city'", $db);
$query++;
while($rs5 = mysql_fetch_array($sql_result5)){
 if($rs5[plot]){
  $plot[$rs5[plot]] = array(
   'color' => $rs5[color],
   'color1' => $rs5[color1],
  );
 }
}

,然后...

foreach($plot as $this_plot){
 $color = $this_plot['color'];
 $color1 = $this_plot['color1'];
 // Do something here
}

或者,在while

内创建网格
$sql_result5 = mysql_query("SELECT * FROM turfs WHERE city = '$city'", $db);
$query++;
while($rs5 = mysql_fetch_array($sql_result5)){ 
 if($rs5[plot]){
  $color = $rs5['color'];
  $color1 = $rs5['color1'];
  // Do something here
 }
}

答案 1 :(得分:0)

$sql_result5 = mysql_query("SELECT * FROM turfs WHERE city = '$city'", $db); $query++;
$plots = array();
$i = 0;
while ($rs5 = mysql_fetch_array($sql_result5)) {  
    $plots[$i] = $rs5;    
    $i++;
} 

//Then when you're rendering...
$i=0;
foreach($plots as $space)
{
    $space['color'];
}

只取决于您希望如何发布信息。您可以创建一个2D数组,但出于您的目的,我认为没有必要。您只需每20个项目创建一个新行。