PDO Fetch Execute


 

PDO Fetch Execute

In this tutorial we will study about PDO Fetch Assoc Execute in PHP, how to access MySQL using PDO Fetch Assoc function, How to retrieve data etc. Examples will make this clearer.

In this tutorial we will study about PDO Fetch Assoc Execute in PHP, how to access MySQL using PDO Fetch Assoc function, How to retrieve data etc. Examples will make this clearer.

PDO Fetch Mode:

We have studied before in the earlier tutorials that how to connect with a database and how to fetch data from the tables, in many times we need a numerical index or an associative index. To do this PDO::query provides a technique called FETCH, which is used with the PDOStatement object.

PDO Fetch Assoc:

PDO::FETCH_ASSOC constant is used to fetch an associative array from the result and returns the column names and field values of the resulting array.

Example:strong>

<?php

header('Content-type:text/html');

$host='localhost';

$user='root';

$password='';

try

{

$dbh=new PDO("mysql:host=$hostname;dbname=db",$user,$password);

$sql="select * from student";

$stmt=$dbh->query($sql);

$result=$stmt->fetch(PDO::FETCH_ASSOC);

echo "<table border=1>";

foreach($result as $key=>$val)

{

echo "<tr><td>".$key."</td>";

echo "<td>".$val."</td></tr>";

}

echo "</table>";

$dbh=null;

}

catch(PDOException $c)

{

echo $c->getMessage();

}

?>

0

 

Output:

Namerose
Roll1

Ads