prepared statement is a very good approach for passing variables to the query with high security and efficiency. So all fine. Just there is a small thing which sometimes makes me uncomfortable.
Actually sometimes my queries are made dynamically. And I don't know how many times should I pass a variable. Suppose this query:
UPDATE user
SET reputation = reputation + (CASE id WHEN :op THEN 2 WHEN :user THEN 15 END)
WHERE id in (:user, :op);
I should pass 2 variables ($user
, $op
) and I have to bind each one them twice:
$sth->bindValue(":op", $op, PDO::PARAM_INT);
$sth->bindValue(":user", $user, PDO::PARAM_INT);
$sth->bindValue(":user", $user, PDO::PARAM_INT);
$sth->bindValue(":op", $op, PDO::PARAM_INT);
Well sometimes that query will be like this:
UPDATE user
SET reputation = reputation + (CASE id WHEN :op THEN 2 WHEN :user THEN 15 END)
WHERE id in (:user, :op),
fee = fee +
(CASE id WHEN :op THEN (SELECT SUM(op_val) FROM money WHERE id = :post_id)
WHEN :user THEN (SELECT SUM(user_val) FROM money WHERE id = :post_id)
END)
WHERE id in (:user, :op);
For query above, I should pass 1 more variable ($post_id
). In other word 4 more bind value:
$sth->bindValue(":op", $op, PDO::PARAM_INT);
$sth->bindValue(":user", $user, PDO::PARAM_INT);
$sth->bindValue(":op", $op, PDO::PARAM_INT);
$sth->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$sth->bindValue(":user", $user, PDO::PARAM_INT);
$sth->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$sth->bindValue(":user", $user, PDO::PARAM_INT);
$sth->bindValue(":op", $op, PDO::PARAM_INT);
See? That's hard for me to pass variables to a dynamic query. I mean I have to pass one variable several times. Well is there any other approach to validate a variable instead of prepared statement?