How can one effectively debug a MySQL query in PHP to identify errors and ensure proper execution?

To effectively debug a MySQL query in PHP, you can enable error reporting to display any SQL errors that may occur. Additionally, you can use functions like mysqli_error() to retrieve detailed error messages for your queries. It's also helpful to echo or print out the generated SQL query to ensure it's correct before executing it.

// Enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Your SQL query
$sql = "SELECT * FROM table_name WHERE column = 'value'";

// Print out the generated SQL query
echo $sql;

// Execute the query
$result = $mysqli->query($sql);

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

// Process the query result
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

// Close the connection
$mysqli->close();