What are the potential benefits of using MySQLi or PDO over MySQL for database connections in PHP?
When working with databases in PHP, it is recommended to use MySQLi or PDO instead of the older MySQL extension due to better security features and support for prepared statements, which help prevent SQL injection attacks. Both MySQLi and PDO offer object-oriented approaches to interacting with databases, making code more organized and easier to maintain.
// Using MySQLi for database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$conn->close();