Reputation: 769
Having the following code
<?php
$age = get_age(); // a generated or random unsigned integer
$db->prepare("SELECT * FROM Customers WHERE name = :name AND age = :age");
$db->bindValue('name', $_POST['name']);
$db->bindValue('age', $age, PDO::PARAM_INT);
$db->execute();
Should I bind 'age' even if it doesn't come from the user (i.e outside)?
If I have a fixed age or it's somehow generated by me, should I just do this?
<?php
$age = get_age(); // <- Of course I made sure this is an unsigned integer
$db->prepare("SELECT * FROM Customers WHERE name = :name AND age = $age");
$db->bindValue('name', $_POST['name']);
$db->execute();
Are there pros and cons for each or is it just personal preference?
Upvotes: 3
Views: 410
Reputation: 157919
Should I bind "internal" values when preparing queries in PDO?
Yes.
You should understand the difference between a silly artificial example and a mature real life code during its lifetime span.
If you want to learn how to write a mature code, consider the following:
Upvotes: 6
Reputation: 399
This is just a personal preference, in this case. And I think this is better for understanding the query when this is a big query. But, if a day someone change the function get_age() to retrieve the data by user, this could be dangerous.
Upvotes: 0
Reputation: 73
Yes, you need to bind in your context due to the usage parametter in your sql statement (see: http://php.net/manual/fr/pdostatement.bindvalue.php).
Alternatively, you could do:
<?php
$age = get_age(); // <- Of course I made sure this is an unsigned integer
$sth= $db->prepare("SELECT * FROM Customers WHERE name = ? AND age = ?");
$values = array("john", $age);
$sth->execute($values);
Upvotes: 1