Search code examples
phpmysqlpdomysqlisql-injection

Preventing SQL injection with PDO or MySQLi


I have read the following post, and have some questions: How can I prevent SQL injection in PHP?

I see you can choose between PDO and MySQLi. Is there any difference, and how do I choose between them?

In the example code they use :name for PDO queries and ? for MySQLi. What shall I replace those with? Just a PHP variable?

Finally, how do I prepare to begin using PDO on my website? Is there any thing I need to install or add, or can I just begin, and use the same code as provided in the examples?

Thank you


Solution

  • Go with PDO, you'll be glad you did.

    Back in ancient times of PHP 5.0, Mysqli was part of PHP, but PDO had to be installed separately from PECL.

    Since PHP 5.1, PDO has been part of the standard PHP extensions. Both should be available on any modern PHP installation. I've heard of a few hosting companies that still don't enable PDO, but IMHO that indicates the hosting provider isn't keeping up with modern software, and it's a reason to switch to a different hosting provider, not a reason to use Mysqli.

    PDO has only an object-oriented usage, whereas Mysqli supports both procedural and object-oriented usage.

    PDO supports multiple drivers for different brands of RDBMS, whereas Mysqli of course is only for MySQL.

    There are a few cases where writing code in PDO is simpler. For example if you're coding a general-purpose function to insert into any table, with a variable number of columns, it's easier to pass an array of parameters to a prepared statement with PDO than the gymnastics you have to do with Mysqli.