Skip to content
PHP Logo

What best practices should be followed when configuring the database connection in a PHP script like PHPvoting 2.5?

When configuring the database connection in a PHP script like PHPvoting 2.5, it is important to follow best practices to ensure the security and efficiency of the application. This includes using PDO (PHP Data Objects) to connect to the database, using prepared statements to prevent SQL injection attacks, and storing sensitive information such as database credentials in a separate configuration file outside of the web root.

php
// Database configuration
$host = 'localhost';
$dbname = 'database_name';
$username = 'username';
$password = 'password';

// Create a PDO connection
try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Error connecting to the database: " . $e->getMessage());
}