What are common issues when retrieving data from an SQL database in PHP and how can they be resolved?

Common issues when retrieving data from an SQL database in PHP include incorrect SQL syntax, connection errors, and data not being fetched properly. These issues can be resolved by ensuring the SQL query is correctly formatted, establishing a successful database connection, and using appropriate PHP functions to fetch and display the data.

// Example of retrieving data from an SQL database in PHP

// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

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

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

// SQL query to retrieve data
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

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

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