What are the advantages of using a current library like mysqli or PDO over mysql_connect in PHP?
Using a current library like mysqli or PDO over mysql_connect in PHP offers several advantages, including improved security through the use of prepared statements to prevent SQL injection attacks, better support for newer MySQL features, and the ability to work with multiple database systems, not just MySQL. Additionally, mysqli and PDO provide object-oriented interfaces, making it easier to work with databases in a more structured and efficient manner.
// Using PDO to connect to a MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}