0

I currently use mysql_real_escape_string to escape variable in mysql query. I know how to use bindValue, but I have a question about protection when I'm trying to insert table name from variable. For example

$tablename = mysql_real_escape_string($name_from_form);
$get = mysql_query("SELECT * FROM ".$tablename." WHERE keyword='something'");

Can anybody help me with an example of how to do PDO prepared statements which will do the same as above?

galethil
  • 996
  • 8
  • 13

1 Answers1

1

You won't be able to escape the table name (I hope that $tablename isn't coming from an outside source - If it is, you will need to whitelist what table names are allowed). In PDO, your code could look something like:

$allowedTables = array('posts', 'users');
if(!in_array($tablename, $allowedTables)){
    throw new Exception('Invalid table name: ' . $tablename);
}

$keyword = 'something';
$stmt = $dbh->prepare("SELECT * FROM " . $tablename . " WHERE keyword = :keyword");
$stmt->bindParam(':keyword', $keyword);
$stmt->execute();
Wayne Whitty
  • 19,513
  • 7
  • 44
  • 66
  • Thank you, I was thinking about similar fix, but I wasn't sure if there is a better solution. Thanks a lot. – galethil Jan 24 '14 at 13:44