Advertisement
GWibisono

latihan pdo

Apr 8th, 2016
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.66 KB | None | 0 0
  1. <?php
  2. $user='gunawan';
  3. $pass='';
  4. try {
  5.    
  6.     $con = new PDO('mysql:host=localhost;dbname=test', $user, $pass); /*buka koneksi*/
  7.     $con->beginTransaction();
  8. /*=====ADA DATA DI INPUT.. NANTI DIBATALKAN */ 
  9.     $sql="insert into mytable(name) value('SALAH')";
  10.     $res = $con->exec($sql);
  11.     $insertOK= $res!=false ?$res:false;
  12.     if($insertOK){
  13.         echo "OK .. total perubahan ".$insertOK;
  14.     }
  15.     else{
  16.         throw new PDOException('code:'.$con->errorCode().'|error:'.implode("<br/>",$con->errorInfo()));
  17.     }
  18. /*QUERY AWAL*/
  19.     echo "<p>DATA AWAL SEBELUM ROLLBACK</p>";
  20.     $sql = "select name from mytable";
  21.     $res = $con->query($sql);
  22.     if(!$res){
  23.         throw new PDOException('code:'.$con->errorCode().'|error:'.implode("<br/>",$con->errorInfo()));
  24.     }
  25.     else{
  26.         foreach ($res as $row) { /*query dan tampilkan*/
  27.             print $row['name'] . "\t";
  28.             print "<br/>";
  29.         }
  30.     }  
  31. /* ROLLBACK */
  32.     $con->rollBack();
  33. /*QUERY SETELAH ROLLBACK*/
  34.     echo "<p>DATA SESUDAH ROLLBACK</p>";
  35.     $sql = "select name from mytable";
  36.     $res = $con->query($sql);
  37.     if(!$res){
  38.         throw new PDOException('code:'.$con->errorCode().'|error:'.implode("<br/>",$con->errorInfo()));
  39.     }
  40.     else{
  41.         foreach ($res as $row) { /*query dan tampilkan*/
  42.             print $row['name'] . "\t";
  43.             print "<br/>";
  44.         }
  45.     }
  46.    
  47.     $sql="insert into mytable(name) value('satu'),('dua')";
  48.     $res = $con->exec($sql);
  49.     $insertOK= $res!=false ?$res:false;
  50.     if($insertOK){
  51.         echo "OK .. total perubahan ".$insertOK;
  52.     }
  53.     else{
  54.         throw new PDOException('code:'.$con->errorCode().'|error:'.implode("<br/>",$con->errorInfo()));
  55.     }
  56.     $con = null; /*untuk close */
  57.    
  58.    
  59.    
  60. } catch (PDOException $e) {
  61.     print "Error!: " . $e->getMessage() . "<br/>";
  62.     die();
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement