Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQLi & mysql_real_escape_string() Errors

Tags:

php

mysql

mysqli

I am using OOP MySQLi to connect to my database. I have checked my credentials and everything is good to go.

    $mysqli = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DB) or die('There was a problem connecting to the database.');

    if (mysqli_connect_errno()) { 
       printf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()); 
       exit; 
    }

    if ($result = $mysqli->query('SELECT * FROM places WHERE place_id=' . mysql_real_escape_string($_GET['id']))) { 
        while( $row = $result->fetch_assoc() ){ 
            printf("%s (%s)\n", $row['name'], $row['place_id']); 
        } 
        $result->close(); 
    } 

    $mysqli->close();

This code is generating a error:

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access
denied for user '-removed-'@'localhost' (using password: NO) in
/var/www/vhosts/communr.com/httpdocs/pbd/places.php on line 396

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to
the server could not be established in
/var/www/vhosts/communr.com/httpdocs/pbd/places.php on line 396

I can't figure out why I am getting these errors. They started showing when I moved servers recently. I am establishing an SQL connection before the query.

Do you all think some setting could be messed up on my new server?

Thanks!

like image 772
ATLChris Avatar asked Feb 22 '11 16:02

ATLChris


1 Answers

mysql_real_escape_string requires a connection to be established via mysql_connect in order to work. $mysqli->real_escape_string requires a mysqli object to work. So,

Use MySQli::real_escape_string instead:

'SELECT * FROM places WHERE place_id='.$mysqli->real_escape_string($_GET['id']); 

But note that you'd need to quote it in order to be safe:

'SELECT * FROM places WHERE place_id=\''.$mysqli->real_escape_string($_GET['id']).'\''; 

However, since it looks like an integer, you should cast it as such instead of escaping it:

'SELECT * FROM places WHERE place_id='.(int) $_GET['id']; 
like image 199
ircmaxell Avatar answered Oct 25 '22 01:10

ircmaxell