Share on Google+Share on Google+

PDO Fetch Execute

Advertisement
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();

}

?>

 

Output:

Namerose
Roll1

Advertisements

Advertisement

Posted on: April 5, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.