Jump to: navigation, search

PHP MySQLi Fetch Records as an associative array

From w3cyberlearnings

Contents

PHP MySQLi Fetch records as an associative array

Query records as an associative array.

Syntax Fetch Records As Associative Array

$sql = "SELECT id, name, age FROM student";
$result_db = $db->query($sql);
while ($row = $result_db->fetch_assoc()) {
	echo $row['id'];
	echo "<br/>";
        echo $row['name'];
        echo "<br/>";
        echo $row['age'];
        echo "<br/>";
}

Example 1

<?php

define('HOST', 'localhost');
define('USER', 'user2000');
define('PASS', 'password2000');
define('DBNAME', 'w3cyberlearning');

$db = new mysqli(HOST, USER, PASS, DBNAME);

if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") "
. $db->connect_error;
}

$sql = "SELECT id, name, age FROM student";
$result_db = $db->query($sql);

if (!$result_db) {
echo 'Error perform query!';
}

$table =
'<table border="1">
	<tr>
	<td>Id</td>
	<td>Name</td>
	<td>Age</td>
	</tr>';

while ($row = $result_db->fetch_assoc()) {
$table .= '<tr>'
  . '<td>' . $row['id'] . '</td>'
  . '<td>' . $row['name'] . '</td>'
  . '<td>' . $row['age'] . '</td>'
  . '</tr>';
}

$table .='</table>';
echo $table;


$db->close();
?>

Output

Php mysqli fetch associative 1.png

<sidebar>

    • PHP MySQL mysqli|PHP MySQL mysqli
    • PHP MySQLi Connect|PHP MySQLi Connect
    • PHP MySQLi Create Table|PHP MySQLi Create Table
    • PHP MySQLi Insert Records Using Binding|PHP MySQLi Insert Records use Binding
    • PHP MySQLi Fetch Records as an associative array|PHP MySQLi Fetch Records as an associative array
    • PHP MySQLi Fetch All Records|PHP MySQLi Fetch All Records
    • PHP MySQLi Fetch Records And Bind to variables|PHP MySQLi Fetch Records And Bind to variables
    • PHP MySQLi Fetch as object|PHP MySQLi Fetch as object
    • PHP MySQLi Fetch Records Use binding|PHP MySQLi Fetch Records Use binding
    • PHP MySQLi Update Records and Return affected rows|PHP MySQLi Update Records and Return affected rows
    • PHP MySQLi Delete Records Use binding|PHP MySQLi Delete Records Use binding

</sidebar>

Navigation
Web
SQL
MISC
References