Got more questions? Find advice on: ASP | SQL | XML | Windows
in Search
Welcome to RegexAdvice Sign in | Join | Help

escaping mysql queries

Last post 04-02-2008, 4:01 AM by maraja. 0 replies.
Sort Posts: Previous Next
  •  04-02-2008, 4:01 AM 40950

    escaping mysql queries

    hallo,

    I am using a function (PHP/MYSQL) to execute every query in the sites I develop:

        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        #    Executes a query
        #
        function db_query($query, $line='', $file='', $flag='')
        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        {
            global $dbh;

            $exec[0]=@mysql_query($query, $dbh);    # resource ID of the query

            if(!$exec or $exec[0]=='' && $flag=='')
            {
                echo(BuildMySqlString('<div align="center">'.$dbh.'</div><br />'.$query.'<br /><br />File: '.$file.'<br />Line: '.$line.'<br />'));
                exit;
            }
            else
            {
                if(substr($exec[0],0,8)=='Resource')
                {
                    #    if the query includes a LIMIT parameter, $exec[0] is set to that limit
                    #    otherwise to the Resource ID that can be used to get the number of records found
                    #
                    $exec[1]=@mysql_num_rows($exec[0]);    # number of records found
                }
                return($exec);
            }
        }


    I would like to get a regex able to match every kind of mysql queries (select, insert, update, etc.) the function gets so that it can properly add the required slashes.

    This can be easily done with the PHP functions mysql_escape_string/mysql_real_escape_string but it will require to edit all the code preparing the queries...

    These inputs:
    SELECT * FROM database WHERE code=''
    SELECT * FROM database WHERE code<=''
    SELECT * FROM database WHERE code LIKE ''
    should remain as they are.

    This input:
    SELECT * FROM database WHERE code='Site's setting "special"'
    should read:
    SELECT * FROM database WHERE code='Site\'s setting \"special\"'

    The regex should be able to add the backslashes only within the values passed to the WHERE clause.

    Thank you so much in advance for your help! 

    Filed under: ,
View as RSS news feed in XML