Reputation: 805
I was always wondering if it is good practice to bind entire list of values. For example I have to following query:
INSERT INTO messages
(thread_id,message,from_id,to_id,to_viewed,notified,from_deleted,to_deleted,created)
SELECT :threadId,:msg,:fromId,:toId,0,0,0,0,:createdTime FROM messages
WHERE thread_id = :threadId AND to_id=:toId LIMIT 1
In this case would have any sense to bind also notified
, from_deleted
and to_deleted
fields since this is static value, always 0 when inserting new msg?
I need to modify my question. I know that for security reason there is not reason to bind also fields/values that are not generated from user. In my case not reason to bind fileds notified
, from_deleted
and to_deleted
because they are always 0. But my real question is should I bind those fields for other reasons (cache). Will mysql cache entire query statement or only binded parms?
Upvotes: 0
Views: 287
Reputation: 8600
It is really only necessary to as you say bind the parameters (a prepared query) of variables that are from an external source (which you should also strip out html characters, scripts). When you do a prepared query PDO will convert quotes to prevent a sql injection. You can just put your static variables straight into the query because you (developer) know that it's safe for a 0 or 1 to be looked for or even some static string for that matter. The rest is just a matter of having a syntactically correct query.
You can run this query to insert a test row by using sequelpro, phpmyadmin, the mysql cli or any other sql utility (assuming you are running mysql)
INSERT INTO messages
(thread_id,message,from_id,to_id,to_viewed,notified,from_deleted,to_deleted,created)
VALUES (1, 'Blah', 1, 2, 3, 0, 0, 0, '2012-07-21');
PDO Example
try {
$dbh = new PDO($dsn, $user, $password);
$sth = $dbh->prepare('SELECT * FROM messages WHERE thread_id = :threadId AND to_id=:toId LIMIT 1');
$sth->execute(array(':threadId' => $id, ':toId' => $to_id));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Upvotes: 1