How can you fetch the results of a MySQLi query in PHP?
To fetch the results of a MySQLi query in PHP, you can use the `mysqli_query()` function to execute the query and then use `mysqli_fetch_assoc()` or `mysqli_fetch_array()` to retrieve the results row by row. You can loop through the results using a `while` loop until all rows have been fetched.
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Execute the query
$result = $mysqli->query("SELECT * FROM table");
// Fetch and display the results
while ($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"] . " - Column2: " . $row["column2"] . "<br>";
}
// Free the result set
$result->free();
// Close the connection
$mysqli->close();
Related Questions
- How can the output of a MySQL query in PHP be properly displayed and manipulated?
- Are there any specific parameters, such as path and domain, that can be used with setcookie in PHP to address cookie-setting issues across different domains?
- What are the best practices for replacing words without case sensitivity in PHP?