What are some best practices for securely accessing a MySQL database in PHP?
When accessing a MySQL database in PHP, it is important to securely handle database credentials to prevent unauthorized access. One best practice is to store database credentials in a separate configuration file outside of the web root directory. This helps to prevent direct access to the credentials by unauthorized users.
<?php
// Include the database configuration file
include 'config.php';
// Connect to the MySQL database
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}