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

When debugging PHP code, especially when dealing with MySQL queries, it's important to check for syntax errors, connection issues, and data retrieval problems. One best practice is to use error reporting functions like error_reporting(E_ALL) and ini_set('display_errors', 1) to display any errors or warnings. Additionally, using tools like var_dump() or print_r() can help inspect variables and query results to identify any issues.

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

// Connect to 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);
}

// Example MySQL query
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Check for errors in query execution
if (!$result) {
    die("Error: " . $conn->error);
}

// Fetch and display data
while ($row = $result->fetch_assoc()) {
    echo "Name: " . $row["name"] . "<br>";
}

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