What are common issues that can prevent PHP scripts from outputting data from a MySQL database?

Common issues that can prevent PHP scripts from outputting data from a MySQL database include incorrect database connection credentials, SQL syntax errors in the query, and failure to fetch and display the results properly. To solve these issues, ensure that the database connection details are correct, double-check the SQL query for errors, and use appropriate PHP functions to fetch and display the data.

// Correct database connection details
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

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

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

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