Along the same lines of proper coding of my queries to work with prepared statements, I have this query:
$sql = "SELECT *
FROM photos
WHERE g_id = ?
LIMIT $curPage,".$totalPix;
$result = $conn->query($sql) or die(mysqli_error());
$row = $result->fetch_assoc();
The question here is, should I use the prepared statement placeholders for $curPage and $totalPix and if so, would I do it this way:
$sql = "SELECT *
FROM photos
WHERE g_id = ?
LIMIT ?,".?;
$gid = $i; $lm = $v1; $mt = $v2
$stmt = $conn->prepare($randPic);
$stmt->bind_param('iii', $gid, $lm, $mt);
$stmt->bind_result($p_fname);
$stmt->execute();
$stmt->store_result();
$stmt->fetch();
…or are the variables $curPage and $totalPixnot leaving the query open to SQL injection? Many thanks in advance!
You are using the ? on the right place (since it can only be used for variable binding). However it is not safe to simply place
$curPage or $totalPixin your query. I am assuming they have to be integers, so it is not really hard to make that safe.Use
intval($curPage) and intval($totalPix)to be certain they are.However, if you want to allow strings it is a bit more difficult. Not sure if it is thé solution, but my bet is to ‘whitelist’ possible options by checking if it is something you designed it for.
For instance:
SELECT * FROM sometable WHERE $somevar = ?The variable ($somevar) could still be'1 --'which would return all the rows. But most likely you mean $somevar = ‘id’ or $somevar = ’email’. Which can easily be checked by some if statements and it wouldn’t hurt performance. Maybe a little typing, but if your not in the mood to type I suggest using some framework for queries or ORM of some kind.if ($somevar !== 'id') exit('Cannot find entries');at the start of the function or page