How does using PDO in PHP differ from mysqli_connect in terms of database connection and security?
Using PDO in PHP offers a more secure and flexible way to connect to databases compared to mysqli_connect. PDO provides a consistent interface for accessing different types of databases, while mysqli_connect is specific to MySQL. Additionally, PDO supports prepared statements, which help prevent SQL injection attacks.
// Using PDO to connect to a MySQL database
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to database successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Related questions
-
return statement PHP function purpose
-
SQL injection XSS attacks htmlentities
-
PHP IDs manipulation