What steps can be taken to troubleshoot and resolve issues related to accessing and displaying data from a MySQL database in PHP, as seen in the provided code snippet?
Issue: The code snippet provided may not be properly connecting to the MySQL database or fetching the data correctly. To troubleshoot and resolve this issue, ensure that the database connection is established successfully, the SQL query is correct, and the fetched data is properly displayed.
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
$conn = new mysqli($servername, $username, $password, $database);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch data from the database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// Close the database connection
$conn->close();