Skip to content
PHP Logo

What best practices should be followed when connecting to a database using PHP?

When connecting to a database using PHP, it is important to follow best practices to ensure security and efficiency. One key practice is to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to store database credentials in a separate configuration file outside of the web root to prevent unauthorized access.

php
<?php
// Database configuration
$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";
?>