How can one troubleshoot and debug PHP code that is not successfully retrieving data from a database?

One way to troubleshoot and debug PHP code that is not successfully retrieving data from a database is to check the database connection, query syntax, and error handling. Ensure that the database connection is established correctly, the query is written accurately, and any errors are being caught and displayed for troubleshooting.

// Check the database connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Check the query syntax
$sql = "SELECT * FROM table_name";
$result = mysqli_query($conn, $sql);
if (!$result) {
    die("Error in query: " . mysqli_error($conn));
}

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

// Close the connection
mysqli_close($conn);