Reputation: 23
I am using following method for MySQL queries:
$sql = "SELECT * FROM mytable WHERE `myTableId`=" . (int)$myId;
Is this a completely safe method or is there a way to inject some sql into the database with this method? Any better alternative?
Upvotes: 2
Views: 3530
Reputation: 151
make it like this
$sql="select `username` from `users` where id='$newid';";
mysql_query($sql);
here $newid is the int value. The symbol used before and after username, to get this you have to press the key just below esc .
Upvotes: 0
Reputation: 369
No need for the Int if you are just worrying about the mysql injection. To prevent mysql injection you can use mysql_real_escape_string.
What you have right now will block all mysql injection if your mysql condition is only for int but if the situation is like this:
$username = $_GET["username"];
SELECT * FROM customers WHERE username = '$username'
if the $username value is *\' OR 1* your in trouble or i should say your dead
if the $username value is *\'; DELETE FROM customers WHERE 1 or username = * your very dead + doomed
To prevent this from happening use mysql_real_escape_string
$username = mysql_real_escape_string($_GET["username"]);
Upvotes: -2
Reputation: 23876
I would probably use sprintf instead - but I dont see that it is much different from what you are doing. Placing the integer in quotes may also help.
$sql = sprintf("SELECT * FROM mytable WHERE `myTableId`='%d'", $myId);
Should probably add that you may want to deal with the case when conversion to integer fails. So dont have a table zero.
Upvotes: -1
Reputation: 360762
It can lead to unintended consequences, e.g.
$myId = 'blahblahblah';
would result in
... WHERE myTableId=0
maybe not such a big deal in this case, but if (say) you're doing a permissions systme and "super-duper-ultra-high-level-user-with-more-power-than-god" has permission level 0, then it's a nice way to bypass security.
Upvotes: 4
Reputation: 29932
Thís should be perfectly save, without any drawbacks, as long as the input can be casted to int.
Upvotes: 2
Reputation: 9332
If you truly want to avoid SQL injection, your best bet is to use PDO and prepared statements. check out http://www.php.net/pdo and http://www.php.net/manual/en/pdo.prepare.php
Upvotes: 3