r/PHPhelp • u/bottledpee • Apr 19 '21
Solved PDO query differences
what's the difference between:
$sql = "SELECT * FROM credentials WHERE userID != $userID section = $sectionID";
$stmt = $mysqli->prepare($sql);
$stmt->execute();this:
$sql = "SELECT * FROM credentials WHERE userID != ? section = ? ";
$stmt = $mysqli->prepare($sql);
$stmt->execute([$userID , $section]);and this:
$sql = "SELECT * FROM credentials WHERE userID != :userid section = :section ";
$stmt = $mysqli->prepare($sql);
$stmt->execute(
array(
':userid' => $userID,
':section' => $section,
)
);is there some kind of speed or security differences?
what's the industry standard when it comes to these?
6
u/Sergiolibe Apr 19 '21
First of all I think you are missing an AND between userID and section.
The first one is vulnerable to SQL injection (for example passing "3; DELETE FROM users;" as $sectionID).
The second and third ones are not, because they are prepared statements. However, in the second you are passing the variables as generic signa (?) so you HAVE to respect the order (if you change the order in the array that WILL affect what values are passing to each "?" symbol) , in the third one you are using unique Symbols (:some) so you pass a hashmap (Key value array) with the values of those Symbols and the order doesn't matter (you can define the pair ':userid' => $userID after section one).
2
u/bottledpee Apr 19 '21
sorry i fixed it within my code now thank you!
this is really helpful thank you!
5
u/damiankw Apr 19 '21
The first has no parsing of data, it can be influenced by SQL Injection (i think you should be able to read more here: https://stackoverflow.com/questions/134099/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection)
The second protects against SQL Injection by the built in processes in the call, but is a one-for-one in-line array, if you put $section before $userID in your execute() it will get the variables mixed up.
The third protects against SQL Injection as above, but recognises the names of your arrays, so you can put $userID after $section in your execute() as long as they match with the corresponding :userid or :section
1
2
u/dabenu Apr 19 '21
I already see 2 good answers, but want to add that the 3rd option won't work, as mysqli does not support named parameters. You will have to use a wrapper like PDO to use named parameters like that.
1
14
u/Atulin Apr 19 '21
Is open for SQL injection, throw it into trash
Uses prepared statements with positional parameters
Uses prepared statements with named parameters, and the old array syntax
I'd do
and name the db object properly,
$pdo, not$mysqli, to avoid confusion