What best practices should be followed when establishing a connection with a database in PHP?
When establishing a connection with a database in PHP, it is important to follow best practices to ensure security and efficiency. This includes using prepared statements to prevent SQL injection attacks, using a secure method to store database credentials, and properly handling errors that may occur during the connection process.
<?php
$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";
?>