How can errors be effectively debugged in PHP when working with MySQL queries?

To effectively debug errors in PHP when working with MySQL queries, it is important to enable error reporting, check for syntax errors, and use functions like mysqli_error() to get detailed error messages. Additionally, echoing or logging query strings can help identify any issues with the SQL statements being executed.

// 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 = mysqli_connect($servername, $username, $password, $dbname);

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

// Example MySQL query
$sql = "SELECT * FROM table WHERE id = 1";
$result = mysqli_query($conn, $sql);

// Check for errors
if (!$result) {
    echo "Error: " . mysqli_error($conn);
} else {
    // Process results
    while ($row = mysqli_fetch_assoc($result)) {
        echo "Name: " . $row["name"];
    }
}

// Close connection
mysqli_close($conn);