简体   繁体   中英

How can I use mysql connection if connection is made in a php class and the function mysqli_real_escape_string is used in a separate functions file?

I am working on a project in which I am using mysqli extension. I have made mysql connection in a PHP class called Connect.class.php like this -

// connect to db
    public function connect()
    {
        $this->con = @mysqli_connect($this->db_host, $this->db_username, $this->db_password, $this->db_name) or die("Couldn't connect! " . mysqli_connect_error());
        return $this->con;
    }

And I have one another file called functions.php in which I am sanitizing the input data like this -

// filter user input data
function filter_data($input)
{
    $sanitized_data = mysqli_real_escape_string(connection, htmlspecialchars(trim($input), ENT_QUOTES, "UTF-8"));
    return $sanitized_data;
}

Now the above code will not work since it has not correct connection parameter. I am not understanding how can I provide it proper connection that is made from my PHP class Connect.class.php. Since the property of an object can not be used in a function of a separate file ie i cant use $this->con.

If I use simple mysql in place of mysqli then there is no problem at all since mysql_real_escape_string() doesn't need connection as a necessary parameter. So what to do in this situation?

You can do it by more than one way :

1.1- Try putting the escape function inside the connect class, inside a function.

//Make a function _escape($str) and put mysqli_real_escape_string($this->con,$str) in it
//Connect.class.php
public function _escape($str){
     return mysqli_real_escape_string($this->con, htmlspecialchars(trim($input), ENT_QUOTES, "UTF-8"));
}

1.2.1 (Sub method 1) Create an object of connect inside the function and run the escape method

// filter user input data
function filter_data($input)
{
    $db = new Connect();
    $db->connect();
    return $db->_escape($input);
}

1.2.2 (Sub method 2) Just run the escape method outside filter_data, don't use this function any more

$db = new Connect();
$db->connect();
$filtered = $db->_escape($input);

2.1 Use the same approach as in one but don't put the escape function inside connect just make an extended class(Example dbFilter) and put it in there

3.1 Use the connection object return by connect function

// altered filter user input data
function filter_data($input, $conn)
{
    $sanitized_data = mysqli_real_escape_string($conn, htmlspecialchars(trim($input), ENT_QUOTES, "UTF-8"));
    return $sanitized_data;
}

//call it
$db = new Connect();
$conn = $db->connect();
filter_data($input, $conn);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM