[Solved] MySQL INJECTION Solution


Reinventing the wheel and reinventing it the Wrong Way (TM).

  • First of all, there are parametrized queries (available for PHP in MySQLi extension); if that’s not an option, there’s mysql_real_escape_string. This is the main issue – check for already available options before deciding to implement them on your own.
  • Second, you are trying to call PHP functions in SQL, what you wanted was probably something like 'SELECT * FROM ' . safeQ($_GET['query'])
  • Third, you’ve broken all indexing and search on data containing your “evil words”, say hello to performance problems and crazy workarounds.

Edit: To address the example you’re giving in comments:

$v="1; DROP tbl;\";DROP tbl" // oh look, an SQL injection attempt!
$s="SELECT * FROM tbl WHERE ID=".$v; // SQL injection, no doubt

// if ID is an integer field, make it an integer. Simple, secure, and fast.
$s="SELECT * FROM tbl WHERE ID=".(int)$v; 
// $s == 'SELECT * FROM tbl WHERE ID=1' // see PHP manual for explanation of type casting

// if ID is a string field, escape it. Simple, secure, and still plenty fast.
$s="SELECT * FROM tbl WHERE ID="".mysql_real_escape_string($v) . '"';
// $s == 'SELECT * FROM tbl WHERE ID="1; DROP tbl;\";DROP tbl"'; 
// See? No injection, as the quote is *escaped*

4

solved MySQL INJECTION Solution