如何使用mysqli_real_escape_string转义单引号?

时间:2016-03-04 05:52:10

标签: mysql codeigniter

我的代码是这样的:

我的城市阵列(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&#ns; 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个....

解决我问题的任何解决方案?

非常感谢

1 个答案:

答案 0 :(得分: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);
}