Why is it recommended to use mysqli or PDO instead of mysql functions in PHP for database connections?
Using mysqli or PDO instead of mysql functions in PHP is recommended because the mysql extension is deprecated as of PHP 5.5.0 and removed in PHP 7. It is no longer maintained and lacks important security features. Both mysqli and PDO offer more secure ways to interact with databases, support prepared statements to prevent SQL injection attacks, and provide object-oriented interfaces for easier database manipulation.
// Using mysqli to connect to a MySQL database
$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";