-1

I have some PHP code that inserts data to MySQL database using MySQLi. PHP code:

  function insert_db($lat, $lng, $date, $user){
  require('db_info_table.php');
  $conn = mysqli_connect($servername, $username, $password, $dbname);
  if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
    return false;
  }
  $lat  = mysql_real_escape_string($lat); // Sanitize data to prevent SQL injection
  $lng  = mysql_real_escape_string($lng);
  $date  = mysql_real_escape_string($date);
  $user  = mysql_real_escape_string($user); // << ERROR
  $sql = "INSERT INTO table (lat, lng, date, user)
  VALUES ('$lat', '$lng', '$date', '$user')";

  if (mysqli_query($conn, $sql)) {
    return true;
  } else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    return false;
  }
  mysqli_close($conn);
  }

The connection details are located in a separate file in the same directory and it looks like this

  $servername = "localhost";
  $username = "user123";
  $password = "pass123";
  $dbname = "db123";

And I get these errors, I'm pretty sure one leads to another

mysql_real_escape_string(): Access denied for user 'unset_username'@'localhost' (using password: NO)
mysql_real_escape_string(): A link to the server could not be established in

And both errors appear on same line(look at the code).

bcesars
  • 1,016
  • 1
  • 17
  • 36
Pancake_M0nster
  • 267
  • 5
  • 18
  • possible duplicate of ["Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function](http://stackoverflow.com/questions/6445917/connect-failed-access-denied-for-user-rootlocalhost-using-password-yes) – Robert Rossmann Mar 18 '15 at 19:33

1 Answers1

2

It seems that you're connecting to server using mysqli library but then trying to use function from mysql library to secure you string. Use mysqli_real_escape_string() instead.

It basicaly doing the same thing as mysql_real_escape_string() but takes two params: first is connection link and second is variable that needs to be secured. So your code will look like this:

  $lat  = mysqli_real_escape_string($conn, $lat);
  $lng  = mysqli_real_escape_string($conn, $lng);
  $date  = mysqli_real_escape_string($conn, $date);
  $user  = mysqli_real_escape_string($conn, $user);
sota
  • 365
  • 3
  • 8
  • 1
    *"Use `mysqli_real_escape_string()` instead."* - They may not know exactly what to do with that. Best to explain a bit more as to "how" to use it. – Funk Forty Niner Mar 18 '15 at 19:17