How can one ensure proper database connection and permission handling in PHP scripts to avoid errors?

To ensure proper database connection and permission handling in PHP scripts, it is important to establish a secure connection to the database using correct credentials and handle permissions appropriately. This can be achieved by setting up a dedicated user with restricted privileges in the database management system and using prepared statements to prevent SQL injection attacks.

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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

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

// Perform database operations here

// Close connection
$conn->close();
?>