What are some best practices for debugging PHP code, especially when dealing with MySQL errors?

When debugging PHP code, especially when dealing with MySQL errors, it is important to enable error reporting to display any errors that may occur. Additionally, using functions like mysqli_error() can help identify specific MySQL errors. It is also helpful to break down the code into smaller parts and test each part individually to isolate the issue.

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Connect to MySQL database
$host = 'localhost';
$user = 'username';
$password = 'password';
$database = 'dbname';

$conn = mysqli_connect($host, $user, $password, $database);

// Check for connection errors
if (!$conn) {
    die('Connection failed: ' . mysqli_connect_error());
}

// Query database
$sql = "SELECT * FROM table";
$result = mysqli_query($conn, $sql);

// Check for query errors
if (!$result) {
    die('Query failed: ' . mysqli_error($conn));
}

// Process results
while ($row = mysqli_fetch_assoc($result)) {
    // Do something with the data
}

// Close connection
mysqli_close($conn);