When working with PHP and databases, security comes first. Older connection methods (such as `mysql_connect`) are obsolete and insecure. Today we use PDO (PHP Data Objects), which enables secure and object-oriented database interaction.
Main Advantages of the PDO Extension
- Prepared Statements: They prevent SQL injections by separating the command from the data.
- Universality: If you decide to switch from MySQL to PostgreSQL, most of your code will remain the same.
- Advanced Error Handling: PDO uses "Exceptions," which makes bug hunting much easier.
Comparison of Connection Methods
| Feature | MySQLi | PDO |
|---|---|---|
| Security | Good | Excellent (standard) |
| Prepared Statements | Supported | Supported (easier to use) |
| Multiple Databases | Only MySQL | 12 different databases |
Code for a Secure Connection (db.php)
Save this code in the db.php file and include it in your projects:
$host = 'localhost';
$db = 'your_database';
$user = 'username';
$pass = 'password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
// Connection established!
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}