如何将变量的值分配给之前的另一个变量?

时间:2012-05-19 13:53:30

标签: php mysql variables

我的代码在这里:

$array_letter = array("A","B","C","Ç","D","E","F","G","H","I","İ","J","K","L",
                      "M","N","O","P","R","S","Ş","T","U","Ü","V","Y","Z");

$sql = "SELECT id,city  FROM city WHERE city LIKE '" .$array_letter[$i]."%'";

在这些代码之后:

for ($i=0;$i<27;$i++) {
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {

 echo "<h3>".$row['city']."</h3>";

   }    
}

$ sql没有意义,因为$array_letter[$i]无法在那里工作。但是$ sql必须是这些代码的顶部才能进行设计。因为我编码switch-case statement。根据请求,$sql将因此而改变我无法在for循环下编写$sql。但我所有的疑问都取决于$array_letter。如何让$array_letter工作?

3 个答案:

答案 0 :(得分:4)

您应该使用mysqli驱动程序和准备好的语句:

$st = $mysqli->prepare("SELECT id,city FROM city WHERE city LIKE ?'");
for ($i=0;$i<27;$i++) {
  $st->bind_param("s", $array_letter[$i].'%');
  $st->execute();
  $result = $st->get_result();

  while ($row = $result->fetch_assoc()) {
    echo "<h3>".$row['city']."</h3>";
  }  
}

虽然对于这种情况,我建议只做一个大查询,因为看起来你得到了所有东西:SELECT id,city FROM city ORDER BY city ......

出于教育目的,另一种方法是做一些事情:

$sql = "SELECT * FROM foo WHERE bar='%s'";
mysql_query(sprintf($sql, "42"));

这在其他情况下非常有用,但同样,如果您正在编写SQL,请使用预准备语句,因为它们可以更优雅地解决此问题,同时提供额外的保护,帮助防止SQL注入攻击并最大限度地减少SQL解析服务器的数量必须这样做。

答案 1 :(得分:1)

你应该使用准备好的陈述,就像马修在他的回答中提到的那样。

否则考虑这个(使用PHP 5.3闭包):

$sql = function($i) use ($array_letters) {
    return "SELECT id,city  FROM city WHERE city LIKE '" .$array_letter[$i]."%'";
}

然后在你的循环中:

mysql_query($sql($i));

答案 2 :(得分:0)

这有助于减少数据库调用。

$array_letter = array("A","B","C","Ç","D","E","F","G","H","I","İ","J","K","L",
                  "M","N","O","P","R","S","Ş","T","U","Ü","V","Y","Z");
for($i=0;$i<count($array_letter);$i++){
if($i!=count($array_letter)-1)
$qstring.="city like '".$array_letter[$i]."%' or ";
 else
$qstring.="city like '".$array_letter[$i]."%'";
}
$sql = "SELECT id,city  FROM city WHERE ".$qstring;
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<h3>".$row['city']."</h3>";
  }