PHP

How safe PDO is to connect to a database?

April 7, 2022

How safe PDO is to connect to a database?

In this article we will learn how safe PDO is to connect to a database in PHP, what are its advantages and disadvantages in relation to other ways

Is PDO the safest way to connect to a database thumb

Hey you programmer, ok? Let’s learn more about PHP and PDO!

We should always opt for PDO over mysql_*, however mysqli which is a newer version of mysql_* and it has a high security level too

What will differentiate above any way of connecting to a database is the handling of data that comes  from the user

If you can predict all SQL Injection failures and other database hacks, it doesn’t matter if you use PDO and mysqli

Which by itself already has tricks to protect from possible code injections

In this topic I comment on the mysqli x PDO issue, it’s worth taking a look to understand the real difference between both libs

Prepared Statements

It is a feature present in the PDO so that the parameters of a query are not entered into it directly

And yes, prepared, so that any malicious intent can be eliminated.

And then mounted in a query and then applied to the Bank

Check out this example:

<?php

/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');

$sth->execute(array(150, 'red'));

$red = $sth->fetchAll();

$sth->execute(array(175, 'yellow'));

$yellow = $sth->fetchAll();

?>

Directly from the PDO documentation

Note that the question marks (?), will be replaced in the future by the data sent by the system and then the query is executed, this is the most security layer of PDO

Mysql_* did not have this function, executing the query with the parameters that came from the request and causing problems

But this lib has already been discontinued and should not be used, and also realize that it is not the same as mysqli

Conclusion

In this article we learned how safe PDO is to connect to a database

Which is more secure than mysql_*, but it almost matches mysqli

One of the great advantages is the prepared statements, which allows the query to be prepared before being executed.

Enabling removal of any code injection in this preparation step

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x