In what situations should mysqli or PDO be preferred over "normal" mysql_xxx functions in PHP?
mysqli or PDO should be preferred over "normal" mysql_xxx functions in PHP when working with databases due to their improved security features, support for prepared statements to prevent SQL injection attacks, and compatibility with multiple database systems. Additionally, mysqli and PDO offer object-oriented approaches to database interactions, making code more maintainable and readable.
// 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);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}