What are the best practices for connecting to a database in PHP to avoid errors?
When connecting to a database in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure data integrity. Additionally, always remember to handle connection errors gracefully by using try-catch blocks or error handling functions. Finally, make sure to close the database connection when it is no longer needed to free up resources.
<?php
$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();
}