php 中的 Mysql 参数化查询


Mysql parameterized queries in php

我有一些MYSQL接口的php代码,

代码是:

      $DBTYPE = 'mysql';
      $DBHOST = 'localhost';
      $DBUSER = 'tuser';
      $DBPASSWORD = 'password';
      $DBNAME = 'dbname';
      $link = mysql_connect($DBHOST, $DBUSER, $DBPASSWORD);
      mysql_select_db($DBNAME); 
      if (!$link) {
          die('Could not connect: ' . mysql_error());
      }
 //IMG**0**
       $hotelc = $hotelCodes[**0**];    
      $result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
  if(!$result) {
      die("Database query failed: " . mysql_error());
  }
  while ($row = mysql_fetch_array($result)) {
      $ImageURL**0** = $row["ImageURL"];
  }
  //IMG**1**
       $hotelc = $hotelCodes[**1**];    
      $result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
  if(!$result) {
      die("Database query failed: " . mysql_error());
  }
  while ($row = mysql_fetch_array($result)) {
      $ImageURL**1** = $row["ImageURL"];
  }
..........................
//IMG**x**
       $hotelc = $hotelCodes[**x**];    
      $result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
  if(!$result) {
      die("Database query failed: " . mysql_error());
  }
  while ($row = mysql_fetch_array($result)) {
      $ImageURL**x** = $row["ImageURL"];
  }

每个代码行上的重复值以粗体显示。

如何在php.n中创建Mysql参数化查询以避免写入所有行。我需要从找到$hotelc的Flat_table中提取~100 $ImageURL。

例如,

您必须重复$N次:

for($i=0; $i<$N; $i++)
{
    $hotelc = $hotelCodes[ $i ];    
    $result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
    if(!$result) {
        die("Database query failed: ".mysql_error());
    }
    while ($row = mysql_fetch_array($result)) {
        ${'ImageURL'+$i} = $row["ImageURL"];
    }
}

要循环,请使用for

for($n=0; $n<100; $n++){
  $hotelc = $hotelCodes[$n];    
  $result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
  if(!$result) {
      die("Database query failed: " . mysql_error());
  }
  while ($row = mysql_fetch_array($result)) {
      $ImageURL[$n] = $row["ImageURL"];
  }
}

但是循环内部的内部函数效率低下,因为 mysql 查询将被执行 100 次。您可以使用 mysql 中的IN()语法查询所有ImageURL

//Wrap all hotelCodes into one string for query, like ["a","b"] to "'a','b'"
$len = count($hotelCodes);
foreach($hotelCodes as $key=>$code){
 $hotelCodes[$key] = "'".$code."'";
}
$codesStr = implode(",", $hotelCodes);
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode IN (".$codeStr.")", $link);
//Other things...

在编写函数时,您需要寻找共性。此外,您希望最大程度地减少数据库交互。为了不推荐使用,我将假设$link使用mysqli_connect()

$ImageURL = array();
$list = implode('", "', $hotelCodes);
$result = mysqli_query($link, 'SELECT ImageURL FROM Flat_table where HotelCode IN "' . $list . '"');
while($row = mysql_fetch_assoc($result)) {
     $ImageURL[] = $row["ImageURL"];
}

仅运行一个查询,然后循环遍历结果,生成关联数组。因此,echo $ImageURL[0];将输出您的第一个 URL。