2016-03-04 89 views
0

我的代碼是這樣的:如何使用mysqli_real_escape_string轉義單引號?

我的城市的數組(echo '<pre>';print_r($city);echo '</pre>';die();):

Array 
(
    [0] => Array 
     (
      [CityCode] => 14879 
      [CityName] => Soldeu 
     ) 

    [1] => Array 
     (
      [CityCode] => 14881 
      [CityName] => Ari'nsal 
     ) 

    [2] => Array 
     (
      [CityCode] => 14882 
      [CityName] => El Tarter 
     ) 

    [3] => Array 
     (
      [CityCode] => 14883 
      [CityName] => Grau Roig 
     ) 

    [4] => Array 
     (
      [CityCode] => 175198 
      [CityName] => Llorts 
     ) 

) 

在城市代碼:14881,城市名稱:Ari'nsal

它在字符串單引號。

我嘗試這樣的代碼:

$date = date('Y-m-d H:i:s'); 

      $sql = "INSERT INTO hotel_search_city (nation_code, city_code, city_name, created_at, updated_at) values "; 

      $valuesArr = array(); 
      foreach($city as $row){ 

       $nation_code = $value->nation_code; 

       $city_code = $row['CityCode']; 
       $city_name = mysqli_real_escape_string($row['CityName']); 
       $created_at = $date; 
       $updated_at = $date; 

       $valuesArr[] = "('$nation_code', '$city_code', '$city_name', '$created_at', '$updated_at')"; 
      } 

      $sql .= implode(',', $valuesArr); 

      $query = $sql; 
      $this->db->query($query); 

存在着錯誤是這樣的:消息:mysqli_real_escape_string()恰好預計2個參數1中給出....

任何解決方案來解決我的問題呢?

非常感謝您

+0

,那麼你需要提供連接:'mysqli_real_escape_string($這個 - >分貝,$ row ['CityName'])'。更好的是,不要使用'mysqli_real_escape_string',而是使用PDO和準備好的語句。 – Amadan

+0

我試試:'mysqli_real_escape_string($ this-> db,$ row ['CityName'])''。存在錯誤:消息:mysqli_real_escape_string()期望參數1是mysqli,對象給出 –

+0

我明白了。然後嘗試'$ this-> db-> mysql_real_escape_string($ row ['CityName'])''。 – Amadan

回答

0
$date = date('Y-m-d H:i:s'); 
$sql = "INSERT INTO hotel_search_city (nation_code, city_code, city_name, created_at, updated_at) values (?, ?, ?, ?, ?)"; 

foreach ($city as $row) { 
    $nation_code = $value->nation_code; 
    $city_code = $row['CityCode']; 
    $city_name = $row['CityName']; 
    $created_at = $date; 
    $updated_at = $date; 

    $fields = array($nation_code, $city_code, $city_name, $created_at, $updated_at); 
    $this->db->query($query, $fields); 
} 

或者如果你沒有使用面向對象的語法

$date = date('Y-m-d H:i:s'); 

foreach ($city as $row) { 
    $fields = array(
     'nation_code' => $value->nation_code, 
     'city_code' => $row['CityCode'], 
     'city_name' => $row['CityName'], 
     'created_at' = $date, 
     'updated_at' = $date 
    ); 

    $this->db->insert('hotel_search_city', $fields); 
} 
+0

我需要你幫忙。看看這裏:http://stackoverflow.com/questions/38175735/how-to-get-data-in-function-extend-controller –