问题
I have the following code:
include $_SERVER['DOCUMENT_ROOT'].'/include/conn.php';
$query = "SELECT title FROM news_event";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_BOTH);
$row_cnt = $result->num_rows;
$result->free();
$mysqli->close();
This is fine if there is only one result as I can just echo $row['title'] but if there are lots of results, how do I get this to loop through and print every row?
I'm sure this is really simple but I'm just not sure what I need to search for in google.
I'm looking for a mysqli equivalent of this:
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
回答1:
just replace it with mysqli_fetch_array
or mysqli_result::fetch_array
:)
while($row = $result->fetch_array())
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
Almost all mysql_*
functions have a corresponding mysqli_*
function..
回答2:
Simple mysqli solution:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT * FROM table WHERE 1');
while ( $rows = $resource->fetch_assoc() ) {
print_r($rows);//echo "{$row['field']}";
}
$resource->free();
$db->close();
With Error Handling: If there is a fatal error the script will terminate with an error message.
// ini_set('display_errors',1); // Uncomment to show errors to the end user.
if ( $db->connect_errno ) die("Database Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) die('Database Error: '.$db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
Using iterators: Support was added with PHP 5.4
$db = new mysqli('localhost','user','password','database');
foreach ( $db->query('SELECT * FROM table') as $row ) {
print_r($row);//echo "{$row['field']}";
}
$db->close();
Fetch a single record: This code does not require a loop.
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();
回答3:
Use:
while ($row = $result->fetch_array(MYSQLI_BOTH)) {
// Look inside $row here, do what you want with it.
}
Look at the associative array examples here (should correspond with fetch_array() versions as well):
http://php.net/manual/en/mysqli-result.fetch-assoc.php
来源:https://stackoverflow.com/questions/12647154/mysqli-query-results-to-show-all-rows