sql fetch assoc row code example
Example 1: mysqli fetch assoc
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
$result->free();
}
$mysqli->close();
?>
Example 2: how to reverse fetch assoc in php
while($row = mysql_fetch_assoc($result)){
$items[] = $row;
}
$items = array_reverse($items ,true);
foreach($items as $item){
echo $item['time']." - ".$item['username']." - ".$item['message'];
}
$query = mysql_query("SELECT * FROM (
SELECT time, username, message
FROM messages ORDER BY time
DESC LIMIT 10) result
ORDER BY time ASC
");