mysql - 如何使用 mysqli_real_escape_string 转义单引号?

标签 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'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 个......

有什么办法可以解决我的问题吗?

非常感谢

最佳答案

$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);
}

关于mysql - 如何使用 mysqli_real_escape_string 转义单引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35788917/

相关文章:

php - Codeigniter Framework 中的语言问题

php - 在 Codeigniter View 中加载数据

css - 在 CodeIgniter 中使用动态样式表

php - CodeIgniter 中 select_avg() 的小数位数

mysql - 如何在 MySQL 中使用 GROUP_CONCAT 显示整列值

MySQL 选择 "accumulated"列

javascript - 如何在下拉列表中传递所选值并附加到 site_url 中?

php - Web 服务应用程序 - 应用程序安全性(登录、用户数据等)

mysql:如何获取一个特定列的最后一个值作为子查询的一部分

php - Codeigniter 防止重复数据