user6224087
user6224087

Reputation:

Safe way to write a PDO query

Which of these two is the safe method to write a query?

$stmt = $pdo->prepare("UPDATE tableName SET fieldName = 0");

OR

$stmt = $pdo->prepare("UPDATE tableName SET fieldName = :parameter");
$stmt-> bindValue(':parameter', 0);

I know the 2nd method is way best and I use it whenever I use a $variable in bindValue. But here, I need to use a known integer 0. So, the first process seemed easier as I did not had to write another bindValue statement. But, is it safe?

Upvotes: 0

Views: 57

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157839

Looking at your questions I'd say that you'll definitely benefit from reading the PDO tutorial I wrote, which says:

There are two ways to run a query in PDO. If no variables are going to be used in the query, you can use the PDO::query() method.

and

if at least one variable is going to be used in the query, you have to substitute it with a placeholder, then prepare your query, and then execute it, passing variables separately.

So now you can tell that for this particular query you can use the query() method instead of prepare/execute

$stmt = $pdo->query("UPDATE tableName SET fieldName = 0");

as there is no variables to be used and this no danger at all

Upvotes: 1

Related Questions