codeIgniter use mysql_real_escape_string() instead

2020-03-26 04:40发布

问题:

I have code igniter installed on server with database I want to run the same db on my mac, I used MAMP and I copy the project folder inside htdocs, but I have this error would you please help me!

ErrorException [ 8192 ]: mysql_escape_string(): This function is deprecated; use mysql_real_escape_string() instead.

回答1:

Don't be afraid to change core files, just alter FCPATH/system/database/drivers/mysqli/mysqli_driver.php

function escape_str($str, $like = FALSE)
{
    if (is_array($str))
    {
        foreach ($str as $key => $val)
        {
            $str[$key] = $this->escape_str($val, $like);
        }

        return $str;
    }

    if (function_exists('mysqli_real_escape_string') AND is_object($this->conn_id))
    {
        $str = mysqli_real_escape_string($this->conn_id, $str);
    }
    else
    {
        $str = addslashes($str);
    }

    // escape LIKE condition wildcards
    if ($like === TRUE)
    {
        $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str);
    }

    return $str;
}

I had the same issue


Better solution -> https://ellislab.com/forums/viewthread/228288/ "stated in github that it will be fixed in CodeIgniter 3.0 the fix already exists in that repository"



回答2:

Try this

function escapeString($val) {
    $db = get_instance()->db->conn_id;
    $val = mysqli_real_escape_string($db, $val);
    return $val;
}


回答3:

try this:

$db['development']['hostname'] = 'mysql:host=localhost';
$db['development']['dbdriver'] = 'pdo';

$db['staging']['hostname'] = 'mysql:host=localhost';
$db['staging']['dbdriver'] = 'pdo';

I have update the answer



回答4:

also, to use the function mysqli_real_escape_str, you need the mysqli , to get it

function get_mysqli() { 
$db = (array)get_instance()->db;
return mysqli_connect('localhost', $db['username'], $db['password'], $db['database']);}

The above function returns a mysqli object such that you can use,

$escaped = mysqli_real_escape_string(get_mysqli(),$string);

It works well, not so important here though!



回答5:

It's not goot idea edit core CI files. If you don't want see deprecated warnings from mysql_escape_string, to use mysql_real_escape_string() instead you need open connection with DB. Use db->initialise() in your base controller

class Base_controller extends CI_Controller {
 function __construct() {
     parent::__construct();

    $this->load->database('db_name');
    $this->db->initialize();