I have an application that takes data via a POST request. I am using this data to insert a new row into the database. I know that using mysql_real_escape_string()
(plus removing % and _) is the way to go for strings, but what about integer values? Right now, I am using the PHP function intval()
on them.
However, I wanted to make sure that intval()
is perfectly safe. I can't see a way of an attacker preforming a SQL injection attack when the variables are run through intval()
first (since it always returns an integer), but I wanted to make sure this is the case from people that have more experience than I.
Thanks.
Yes, intval()
is safe. There is absolutely no way to perform an SQL injection when the parameter is converted to integer, because (obviously) the format of an integer does not allow putting SQL keywords (or quotes, or whatever) in it.
The easiest way to prevent SQL injection is to always use prepared statments. Use the mysqli libraries or better yet an ORM such as doctrine etc.
Your queries then become something like:
$stmt = $db->prep_stmt("select * from .... where userid = ? and username = ?");
/* Binding 2 parameters. */
$stmt->bind_param("is", $userid, $username);
$userid = 15;
$username = "don";
/* Executing the statement */
$stmt->execute( ) or die ("Could not execute statement");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With