How can PHP developers efficiently fetch and display data from a MySQL database using MySQLi?

To efficiently fetch and display data from a MySQL database using MySQLi in PHP, developers can use the mysqli_query function to execute SQL queries and retrieve the results. They can then use mysqli_fetch_assoc to fetch the data in an associative array format, making it easy to display the information on a webpage.

// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database_name");

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

// Execute a query to fetch data from a table
$result = $mysqli->query("SELECT * FROM table_name");

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

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