Jump to: navigation, search

PHP MySQL PDO Fetch and Bind Column to variable

From w3cyberlearnings

Contents

PHP PDO Fetch Records and Bind Column with Variable

Fetch Record uses bindColumn to bind with a variable.

Syntax PDO bindColumn

$sql = "SELECT 
         id,
         first_name, 
         last_name,
         email 
	FROM user_infor";

$sq_stat = $db->prepare($sql);
$sq_stat->execute();

// bind column to variable for display
$sq_stat->bindColumn(1, $id);
$sq_stat->bindColumn(2, $firstname);
$sq_stat->bindColumn(3, $lastname);
$sq_stat->bindColumn(4, $email);

while ($sq_stat->fetch()) {
  echo $id. '-'. $firstname. '-'. $lastnmae.'-'.$email.'<br/>';
}

Example 1

<?php
// bind column to variable
$dns = 'mysql:host=localhost;dbname=w3cyberlearning';
$user = 'user2000';
$pass = 'password2000';

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

$sql = "SELECT 
         id,
         first_name, 
         last_name,
         email 
		FROM user_infor
		";

$sq_stat = $db->prepare($sql);
$sq_stat->execute();

// bind column to variable for display
$sq_stat->bindColumn(1, $id);
$sq_stat->bindColumn(2, $firstname);
$sq_stat->bindColumn(3, $lastname);
$sq_stat->bindColumn(4, $email);

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


while ($sq_stat->fetch()) {
	echo '<tr>';
	echo '<td>' . $id . '</td>';
	echo '<td>' . $firstname . '</td>';
	echo '<td>' . $lastname . '</td>';
	echo '<td>' . $email . '</td>';
	echo '</tr>';
}
echo '</table>';
?>

Output

Php mysql pdo fetch 1.png


Related Links


Navigation
Web
SQL
MISC
References