PDO Basic insert,view,update,delete function - Mostlikers

12 February, 2014

PDO Basic insert,view,update,delete function

Nowadays Most of them using Mysql query but  MySQL is old extension officially deprecated. After improve the code to induce on Mysqli and PDO function. follow this tutorials learn how to insert,view and update query using PDO.


PDO - PHP Data Object 

PDO query more productive and write safer and cleaner code. this connect on different vendors. query more security Instead of concatenating escaped strings into SQL. its faster and easily access million database records.

Database connection 

Database connection similar on mysqli query.

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);
    echo 'Connected to Database<br/>';
catch(PDOException $e)
    echo $e->getMessage();

Previously using Die() function that replace on setAttribute() function this code using on check query exception.

Function to check true or false previously check if($db) else echo mysql_error() using this query in pdo function to check db on try and catch method $e is error mode exception variable.

 PDO Fetch(view) query

Fetch query also simple previously statement to fetch while loop statement. PDO replace on foreach statement.

$sql = "SELECT * FROM `datas`";
foreach ($dbh->query($sql) as $row)
    echo $row["name"];
    echo $row["age"];

PDO Insert query

$insert =$dbh->prepare("INSERT INTO datas (name,age,email) values ('$name','$age','$email')");

PDO Update query

$sql = "UPDATE `datas` SET name='".$name."', `age`='".$age."', email='".$email."' where id='".$id."'";
    $statement = $dbh->prepare($sql);

PDO Delete query

$dell = "delete from `datas` where id='".$dele."'";
    $dells = $dbh->prepare($dell);

PDO Similar like mysql query just change some major line otherwise its very easy. below i attached PDO  insert, delete based small program for reference purpose try to PDO Avoid old mysql query.

Click Download Sample PDO Program

No comments:

Post a Comment