-2

I am trying to sanitize my $_GET input but for some reason, mysql doesn't retrieve the data from the DB. If I do this:

$user = mysqli_real_escape_string($connection, $_GET['id']);

//execute query to call user info
$query = "SELECT user
FROM company
WHERE user={$_GET['id']} ";

this will work and the results are displayed; however if I do this:

$user = mysqli_real_escape_string($connection, $_GET['id']);

//execute query to call user info
$query = "SELECT user
FROM company
WHERE user= '$user' ";

I don't get a database error, but nothing shows up.

Am I not sanitizing right? What's going on here? HELP, please!

1 Answers1

0

Best way to avoid such situations is using prepared queries: How can I prevent SQL injection in PHP?

It's very simple and effective:

$q = $db->prepare('SELECT user FROM company WHERE user=?');
$q->bind_param('i', $user);

$q->execute();

$result = $q->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with $row
}

It's cool because it's OOP and it's safe. Some links:

Community
  • 1
  • 1
speccode
  • 1,562
  • 9
  • 11
  • hi Spec, I appreciate your help. I am new to PHP not am that familiar with prepared statement, so the links helped a lot. I am getting this error when iterating your sample: fatal error: Call to a member function fetch_assoc() on a non-object – user2675057 Oct 30 '13 at 21:49
  • Where you connect to DB use this: `$db = new mysqli('localhost', 'my_user', 'my_password', 'my_db');`. Of course fill those placeholders with your username, password and database name. I think you have to fully rebuild your connection with DB. Check "Connection to DB" for more details. – speccode Oct 30 '13 at 21:54