Search code examples
javascriptphpprepared-statementmysql-real-escape-string

"mysql_real_escape_string" error DESPITE connecting to database..what am I doing wrong?


Ok, this is driving me crazy. My PHP version is 5.2.17, MySQL version is 5.1.59

My javascript(jquery)is :

    $(document).ready(function(){$.post("file.php",{"dropTable":tableName}, function(data){});});

which is an ajax call on page load

My "file.php" contains the following code :

    <?php

        require_once"getDBParameters.php";

        $dbParameters = getDBParameters();
        if($dbc = mysqli_connect($dbParameters['db_host'], $dbParameters['db_username'], $dbParameters['db_pass'], $dbParameters['db_name'])){

            if(isset($_POST['dropTable'])){
                $dropTable= $_POST['dropTable'] ;               
                $escapedRealString = mysql_real_escape_string($dropTable, $dbc );

                echo ($escapedRealString );
                exit();
            }
        }
    ?>

I get a PHP error saying :

    mysql_real_escape_string() expects parameter 2 to be resource, object given in file.php on line 9

The same connection works perfectly if I use prepared statements, however, I cannot use a prepared statement in this case since I'm dropping a MYSQL table based on user input :

    DROP TABLE $dropTable

The PHP manual says I cannot use prepared statements like :

    prepare("DROP TABLE ?")

I can assure you that the function "getDBParameters" is working fine. Whats the problem ? Any other solution ?


Solution

  • mysqli_connect
         ^
    mysql_real_escape_string
         ^
    

    You're mixing MySQLi and MySQL functions. They're entirely different, incompatible extensions. Use mysqli::real_escape_string if you have to.