Preventing SQL injecting in a database class

Posted by Josh on Stack Overflow See other posts from Stack Overflow or by Josh
Published on 2010-03-29T19:17:37Z Indexed on 2010/03/29 19:33 UTC
Read the original article Hit count: 102

Filed under:
|
|
|
|

I'm building a database class and thought it'd be a good idea to incorporate some form of SQL injection prevention (duh!). Here's the method that runs a database query:

class DB
{
    var $db_host    = 'localhost';
    var $db_user    = 'root';
    var $db_passwd  = '';
    var $db_name    = 'whatever';

    function query($sql)
    {
        $this->result = mysql_query($sql, $this->link);
        if(!$this->result)
        {
           $this->error(mysql_error());
        } else {
            return $this->result;
        }
    }
}

There's more in the class than that but I'm cutting it down just for this. The problem I'm facing is if I just use mysql_real_escape_string($sql, $this->link); then it escapes the entire query and leads to a SQL syntax error. How can I dynamically find the variables that need to be escaped? I want to avoid using mysql_real_escape_string() in my main code blocks, i'd rather have it in a function.

Thanks.

© Stack Overflow or respective owner

Related posts about php

Related posts about class