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();
Related Questions
- Are there potential pitfalls when trying to simulate a file upload using fsockopen in PHP?
- What are some methods for loading file content into a variable in PHP without the content being output during inclusion?
- What steps can be taken to troubleshoot issues with PHP code that is not displaying images as expected?