PDO(PHP DATA OBJECTS)

PDO:

  •  It defines the extension to perform  lightweight, consistent interface for accessing databases in PHP.
  • It has unic  uniform method of access to multiple databases.
  • Using prepared statements will help protect you from SQL injection
  • Note that you cannot perform any database functions using the PDO extension by itself. you must use a database-specific PDO driver to access a database server.

lets See Insert, update, delete using PDO

Database Table
Create table user(uid int(10), uname varchar(50), email varchar(255),pass varchar(50))
Insert
<?php
$hostname = ‘localhost';
$dbname = ‘student';
$db_username = ‘root';
$db_pass = ”;
try {
$conn = new PDO(“mysql:host=$hostname; dbname=$dbname”, $db_username, $db_pass);
$conn->exec(“SET CHARACTER SET utf8″);
$sql = “INSERT INTO `users` (`uName`, `Email`, `Pass`)
VALUES(‘name’, ’email’, ‘pass’)”;
$count = $conn->exec($sql);
$conn = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Update
<?php
$hostname = ‘localhost';
$dbname = ‘student';
$db_username = ‘root';
$db_pass = ”;
try
{
$conn = new PDO(“mysql:host=$hostname;dbname=$dbname”,$db_username, $db_pass);
$conn->exec(“SET CHARACTER SET utf8″);
$sql = “UPDATE `users` SET `uName`=’X’, `Email`=’y’ where `id`=20″;
$count = $conn->exec($sql);
$conn = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Delete
<?php
$hostname = ‘localhost';
$dbname = ‘student';
$db_username = ‘root';
$db_pass = ”;
try
{
$conn = new PDO(“mysql:host=$hostname; dbname=$dbname”, $db_username, $db_pass);
$conn->exec(“SET CHARACTER SET utf8″);
$sql = “DELETE FROM `users` WHERE `Email` IN(’email’)”;
$count = $conn->exec($sql);
$conn = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if($count !== false) echo ‘Affected rows: ‘. $count;
?>

 

Leave a Reply

Your email address will not be published. Required fields are marked *