Monday, 20 July 2015

PDO tutorials

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.

<?php
$hostname='localhost';
$username='root';
$password='';
$dbname='design';
try {
    $dbh = new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    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')");
    $insert->execute();

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

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

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.

0 comments:

Post a Comment