What are the potential security risks of directly connecting a PHP web application to a remote database?

Directly connecting a PHP web application to a remote database can expose sensitive information such as database credentials, making it vulnerable to SQL injection attacks. To mitigate this risk, it is recommended to use a secure method such as using environment variables to store database credentials and implementing prepared statements to prevent SQL injection.

// Store database credentials in environment variables
$servername = getenv('DB_SERVER');
$username = getenv('DB_USERNAME');
$password = getenv('DB_PASSWORD');
$dbname = getenv('DB_NAME');

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}