How can PHP developers effectively debug and troubleshoot issues in their code, especially when dealing with database queries?

To effectively debug and troubleshoot database query issues in PHP, developers can utilize tools like Xdebug for step-by-step debugging, enable error reporting to catch any syntax or logic errors, and use print_r or var_dump functions to inspect variables and query results. Additionally, developers can log errors to a file or output them to the browser for easier tracking of issues.

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

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

// Sample query
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

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

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

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