Reputation: 429
I'm doing a live search with jQuery and PHP but I'm not sure if my query is vulnerable to SQL injection.
The data is posted into a PHP file while typing characters with the help of jQuery.
$searchData = $_POST['searchData'];
$searchResult = mysql_query("SELECT * FROM songs WHERE songname LIKE '$searchData%' ");
echo $searchResult;
Is this vulnerable to SQL injection?
Upvotes: 1
Views: 3517
Reputation: 59435
Yes, it is vulnerable. But other responders failed to note that along with the normal escaping (like mysql_real_escape_string()
) you also need to escape the % character for LIKE clause!
mysql_real_escape_string(addcslashes($str, "%_"))
The trick to grasp here is that there is nothing like "universal quoting". When quoting, you always quote text for some particular output, like:
like
expression for mysql queryFor each case, you need different quoting, because each usage is present within different syntax context. This also implies that the quoting shouldn't be made at the input into PHP, but at the particular output! Which is the reason why features like magic_quotes_gpc
are broken (never forget to handle it, or better, assure it is switched off!!!).
So, what methods would one use for quoting in these particular cases? (Feel free to correct me, there might be more modern methods, but these are working for me)
mysql_real_escape_string($str)
mysql_real_escape_string(addcslashes($str, "%_"))
htmlspecialchars($str)
json_encode()
- only for utf8! I use my function for iso-8859-2mysql_real_escape_string(addcslashes($str, '^.[]$()|*+?{}'))
- you cannot use preg_quote in this case because backslash would be escaped two times!preg_quote()
Upvotes: 0
Reputation: 272467
Yes, consider if $searchData
is:
Robert'); DROP TABLE songs; --
Upvotes: 9
Reputation: 116
Since you can use tools to manipulate sent $_POST data, yes, it is dangerous.
Either you escape it or use php data objects (PDO) which doesn't need ANY escaping and is what you should use anyway in this time.
Upvotes: 0
Reputation: 586
use mysql_real_escape_string($_POST['searchData'])
, or [PDO] instead mysql_*
Upvotes: 1
Reputation: 3298
Anytime you are taking user input and putting into a query, you should pass it through mysql_real_escape_string
. Better safe than sorry.
Upvotes: 0
Reputation: 13535
Yes You can use this :
$searchData = addslashes( $_POST['searchData'] );
Upvotes: -1
Reputation: 129001
If $searchData
isn't being escaped anywhere, then yes, it's vulnerable.
Upvotes: 0