Jump to: navigation, search

PHP MySQL PDO Fetch ASSOC

From w3cyberlearnings

Contents

PHP PDO::FETCH_ASSOC Fetches records as associative array

PDO:FETCH_ASSOC fetches records as an associative array.

Syntax PDO Fetch Associative Array

$sq = $db->query("SELECT 
         id,
         first_name, 
         last_name,
          email FROM user_infor");

$r = $sq->fetch(PDO::FETCH_ASSOC);

Example 1

<?php
// fetch as associative array
$dns = 'mysql:host=localhost;dbname=w3cyberlearning';
$user = 'user2000';
$pass = 'password2000';

$db = new PDO($dns, $user, $pass);

$sq = $db->query("SELECT 
         id,
         first_name, 
         last_name,
          email FROM user_infor");

echo '<table border="1">';
echo '<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>';

while ($r = $sq->fetch(PDO::FETCH_ASSOC)) {
	echo '<tr>';
	echo '<td>' . $r['id'] . '</td>';
	echo '<td>' . $r['first_name'] . '</td>';
	echo '<td>' . $r['last_name'] . '</td>';
	echo '<td>' . $r['email'] . '</td>';
	echo '</tr>';
}
echo '</table>';
?>

Output

Php mysql pdo fetch 1.png


Related Links


Navigation
Web
SQL
MISC
References