How can one properly include external configuration files in PHP scripts for database connections?

To properly include external configuration files in PHP scripts for database connections, you can create a separate PHP file that contains your database connection details such as hostname, username, password, and database name. Then, use the PHP include or require function to include this external configuration file in your main PHP script where you establish the database connection.

// config.php
<?php
$hostname = "localhost";
$username = "root";
$password = "password";
$database = "my_database";
?>

// main_script.php
<?php
require_once('config.php');

$conn = new mysqli($hostname, $username, $password, $database);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>