I have a column in a MySQL table that can be either 0 or 1. If the user doesn't enter 0 or 1 then I just set the value to 0. I was wondering if this PHP code would be "safe" from SQL injection:
$flag = $_GET["f"];
if ($flag != 1) $flag = 0;
$sql = "SELECT * from table WHERE column=$flag";
$db->query($sql);
I usually use prepared statements, but I was wondering if this code is full-proof. If this can be broken, then I would like to see an example.
No, it isn't safe. Example SQL injection: 1 OR 1 = 1
This is equal to 1, because (int)"1string" === 1
.
I'd consider to explicitely (int)
cast before passing it to the query:
$sql = "SELECT * from table WHERE column=".(int)$flag;