Search code examples
phppdo

Difference between PDO->query() and PDO->exec()


I see that there is both PDO::query() and PDO::exec(). In the page that was linked, it appears that PDO::query() is used for SELECT statements ONLY, and PDO->exec() is used for UPDATE,INSERT,DELETE statements. Why do these methods exist and when to use them?


Solution

  • Regardless of whatever theoretical difference, neither PDO::query() nor PDO::exec() should be used anyway. These functions don't let you bind parameters to the prepared statement and should never be used.

    Use prepare()/execute() instead, especially for UPDATE,INSERT,DELETE statements.

    Please note that although prepared statements are widely advertised as a security measure, it is only to attract people's attention. But their real purpose is proper query formatting. This gives you security too - as a properly formatted query cannot be injected as well - just as a side effect. But again - formatting is a primary goal, just because even innocent data may cause a query error if not formatted properly.