Jump to: navigation, search

PHP MySQL PDO Fetch FUNC

From w3cyberlearnings

Contents

PHP PDO::FETCH_FUNC for fetch records to function

PDO::FETCH_FUNC fetches records to user define function can be very useful when you want to manipulate the result.

Syntax PDO

// function
function people_info($id, $first, $last, $email) {
	manipulate record here within the function body
      ...
}

$sq = $db->query("SELECT 
         id,
         first_name, 
         last_name,
         email 
	FROM user_infor");
foreach ($sq->fetchAll(PDO::FETCH_FUNC, 'people_info') as $r) {
	echo $r; // display the return function after manipulate records
}

Example 1

<?php

// function
function people_info($id, $first, $last, $email) {
	echo '<tr>';
	echo '<td>' . $id . '</td>';
	echo '<td>' . $first . '</td>';
	echo '<td>' . $last . '</td>';
	echo '<td>' . $email . '</td>';
	echo '</tr>';
}

$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>';

foreach ($sq->fetchAll(PDO::FETCH_FUNC, 'people_info') as $r) {
	echo $r;
}
echo '</table>';
?>

Output

Php mysql pdo fetch 1.png


Related Links


Navigation
Web
SQL
MISC
References