I am using a bit of borrowed code, and am concerned for its vulnerability to SQL injection…
// Set the default namespace to utf8
$mysqli->query("SET NAMES 'utf8'");
$userID = $_POST['userID'];
$json = array();
if($result = $mysqli->query("SELECT * FROM towns WHERE userID=".$userID)) {
while ($row=$result->fetch_assoc()) {
$json[]=array(
'townID'=>$row['townID'],
'townName'=>$row['townName']
);
}
}
$result->close();
header("Content-Type: text/json");
echo json_encode(array( 'towns' => $json ));
Question 1: Does $mysqli->query("SET NAMES 'utf8'"); have any form of sql injection assistance?
Question 2: Should I be using some form of real_escape_string?
If I need to use real_escape_string, should I set the var like this:
$userID = $_POST['userID'];
$userID = $mysqli->real_escape_string($userID);
Then, I can use it just like I currently am in my query?
Thanks
Worded this way – definitely NO.
But see the note at the bottom.
You are asking out of delusion that escaping has something to do with injections, while it is not. So, let’s rephrase your question:
Yes.
You have three choices.
$userID = intval($_POST['userID'];)prepare()+execute()methods instead ofquery()and bind your variable usingbind_param().A note regarding the title question.
Yes, in a way.
In some, extremely rare circumstances, it is.
For some rare encodings
real_escape_stringfamily function may fail proper delimiter escaping. To avoid that, one have to set up the client encoding usingset_charsetfamily function,mysqli->set_charset()in your case.