patternphpMinor
Updating quiz statistics in a database
Viewed 0 times
databaseupdatingstatisticsquiz
Problem
I don't see anyway for a SQL attack to happen with its all hard coded.
Solution
Yes, it's secure because you aren't allowing any variable to be inserted as part of a query. However it is horribly inefficient as it violates the DRY principle: you are writing the same code out in a dozen different places.
A better (and perfectly secure by design) approach would be to use a prepared statement via a parameterised data object (PDO), which would allow all the sanitising of the data to happen automatically. See examples here: https://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php
A better (and perfectly secure by design) approach would be to use a prepared statement via a parameterised data object (PDO), which would allow all the sanitising of the data to happen automatically. See examples here: https://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php
$query = "UPDATE Quiz1 SET :score1 = ( :score2 + 1) WHERE Question = :question ";
$statement = $pdo->prepare($query);
$params = array(
'score1' => 'A',
'score2' => 'A',
'question' => 2
);
$statement->execute($params);
foreach ($statement as $row) {
// Do stuff.
}Code Snippets
$query = "UPDATE Quiz1 SET :score1 = ( :score2 + 1) WHERE Question = :question ";
$statement = $pdo->prepare($query);
$params = array(
'score1' => 'A',
'score2' => 'A',
'question' => 2
);
$statement->execute($params);
foreach ($statement as $row) {
// Do stuff.
}Context
StackExchange Code Review Q#13891, answer score: 3
Revisions (0)
No revisions yet.