What are some best practices for using PHP to access MySQL databases?

When accessing MySQL databases using PHP, it is important to follow best practices to ensure security and efficiency. One common best practice is to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to establish a secure connection to the database and properly handle errors to provide a better user experience.

// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Use prepared statements to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Execute the statement
$stmt->execute();

// Handle errors
if ($stmt->error) {
    die("Error: " . $stmt->error);
}

// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

// Close the connection
$stmt->close();
$conn->close();