How can error reporting and debugging techniques be utilized effectively in PHP to troubleshoot issues like SQL query errors?

When troubleshooting SQL query errors in PHP, error reporting and debugging techniques can be utilized effectively by enabling error reporting, checking for SQL errors, and using try-catch blocks to handle exceptions. By enabling error reporting, any SQL errors will be displayed, making it easier to identify and fix issues in the query. Additionally, using try-catch blocks allows for graceful handling of exceptions, providing more detailed error messages when SQL queries fail.

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

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

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

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

// Execute SQL query
try {
    $sql = "SELECT * FROM table_name";
    $result = $conn->query($sql);

    if ($result === false) {
        throw new Exception($conn->error);
    }

    // Process query results
    while ($row = $result->fetch_assoc()) {
        // Do something with the data
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

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