Sunday 10 August 2014

How to fetch the data from database using pdo in Four steps in php



Follow the Steps
Step1:Make a connection.
Step2: Pass the query into prepare() fucntion.
Step3: Execute the prepare statement.
Step4: Create for loop and use the fetch() to retrieve the data.
Note: we already created Database as registration  and table as user

<body>
<center>
<table border="1" cellspacing="1" cellpading>
<tr>
<td>Id</td>
<td>Name</td>
<td>Password</td>
<td>Email</td>
</tr>
 <?php
$hostname='localhost';
$username='root';
$password='';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=registration",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 echo 'Connected to Database<br/>';
$sql= $dbh->prepare("SELECT * FROM user");
$sql->execute();
for($i=0; $row=$sql->fetch();$i++){
echo "<tr><td>".$row["id"]."</td> ";
echo "<td>". $row["name"] ."</td> "; 
echo "<td>".$row["password"]."</td> ";
echo "<td>".$row["email"]."</td></tr>";
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
</table>
</center>
</body>

2 comments: