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:
| Name | rose |
| Roll | 1 |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.