Advertisement
olie480

PDO CRUD

Jun 21st, 2013
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.01 KB | None | 0 0
  1. <?php
  2.  
  3. // Creds go out to Kevin Waterson
  4. // http://www.phpro.org/classes/PDO-CRUD.html
  5. // http://phpro.org/tutorials/Easy-Access-With-PDO-CRUD.html
  6.  
  7.  
  8. class crud{
  9.    
  10.     private $db;
  11.    
  12.     /**
  13.      *
  14.      * Set variables
  15.      *
  16.      */
  17.     public function __set($name, $value){
  18.         switch ($name) {
  19.             case 'username':
  20.                 $this->username = $value;
  21.                 break;
  22.            
  23.             case 'password':
  24.                 $this->password = $value;
  25.                 break;
  26.            
  27.             case 'dsn':
  28.                 $this->dsn = $value;
  29.                 break;
  30.            
  31.             default:
  32.                 throw new Exception("$name is invalid");
  33.         }
  34.     }
  35.    
  36.     /**
  37.      *
  38.      * @check variables have default value
  39.      *
  40.      */
  41.     public function __isset($name){
  42.         switch ($name) {
  43.             case 'username':
  44.                 $this->username = null;
  45.                 break;
  46.            
  47.             case 'password':
  48.                 $this->password = null;
  49.                 break;
  50.         }
  51.     }
  52.    
  53.     /**
  54.      *
  55.      * @Connect to the database and set the error mode to Exception
  56.      *
  57.      * @Throws PDOException on failure
  58.      *
  59.      */
  60.     public function conn(){
  61.         isset($this->username);
  62.         isset($this->password);
  63.         if (!$this->db instanceof PDO) {
  64.             $this->db = new PDO($this->dsn, $this->username, $this->password);
  65.             $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  66.         }
  67.     }
  68.    
  69.    
  70.     /***
  71.      *
  72.      * @select values from table
  73.      *
  74.      * @access public
  75.      *
  76.      * @param string $table The name of the table
  77.      *
  78.      * @param string $fieldname
  79.      *
  80.      * @param string $id
  81.      *
  82.      * @return array on success or throw PDOException on failure
  83.      *
  84.      */
  85.     public function dbSelect($table, $fieldname = null, $id = null){
  86.         $this->conn();
  87.         $sql  = "SELECT * FROM `$table` WHERE `$fieldname`=:id";
  88.         $stmt = $this->db->prepare($sql);
  89.         $stmt->bindParam(':id', $id);
  90.         $stmt->execute();
  91.         return $stmt->fetchAll(PDO::FETCH_ASSOC);
  92.     }
  93.    
  94.    
  95.     /**
  96.      *
  97.      * @execute a raw query
  98.      *
  99.      * @access public
  100.      *
  101.      * @param string $sql
  102.      *
  103.      * @return array
  104.      *
  105.      */
  106.     public function rawSelect($sql){
  107.         $this->conn();
  108.         return $this->db->query($sql);
  109.     }
  110.    
  111.     /**
  112.      *
  113.      * @run a raw query
  114.      *
  115.      * @param string The query to run
  116.      *
  117.      */
  118.     public function rawQuery($sql){
  119.         $this->conn();
  120.         $this->db->query($sql);
  121.     }
  122.    
  123.    
  124.     /**
  125.      *
  126.      * @Insert a value into a table
  127.      *
  128.      * @acces public
  129.      *
  130.      * @param string $table
  131.      *
  132.      * @param array $values
  133.      *
  134.      * @return int The last Insert Id on success or throw PDOexeption on failure
  135.      *
  136.      */
  137.     public function dbInsert($table, $values){
  138.         $this->conn();
  139.         /*** snarg the field names from the first array member ***/
  140.         $fieldnames = array_keys($values[0]);
  141.         /*** now build the query ***/
  142.         $size       = sizeof($fieldnames);
  143.         $i          = 1;
  144.         $sql        = "INSERT INTO $table";
  145.         /*** set the field names ***/
  146.         $fields     = '( ' . implode(' ,', $fieldnames) . ' )';
  147.         /*** set the placeholders ***/
  148.         $bound      = '(:' . implode(', :', $fieldnames) . ' )';
  149.         /*** put the query together ***/
  150.         $sql .= $fields . ' VALUES ' . $bound;
  151.        
  152.         /*** prepare and execute ***/
  153.         $stmt = $this->db->prepare($sql);
  154.         foreach ($values as $vals) {
  155.             $stmt->execute($vals);
  156.         }
  157.                 return $this->db->lastInsertId();
  158.     }
  159.    
  160.     /**
  161.      *
  162.      * @Update a value in a table
  163.      *
  164.      * @access public
  165.      
  166.      *
  167.      * @param string $table
  168.      *
  169.      * @param string $fieldname, The field to be updated
  170.      *
  171.      * @param string $value The new value
  172.      *
  173.      * @param string $pk The primary key
  174.      *
  175.      * @param string $id The id
  176.      *
  177.      * @throws PDOException on failure
  178.      *
  179.      */
  180.     public function dbUpdate($table, $fieldname, $value, $pk, $id){
  181.         $this->conn();
  182.         $sql  = "UPDATE `$table` SET `$fieldname`='{$value}' WHERE `$pk` = :id";
  183.         $stmt = $this->db->prepare($sql);
  184.         $stmt->bindParam(':id', $id, PDO::PARAM_STR);
  185.         $stmt->execute();
  186.     }
  187.    
  188.    
  189.     /**
  190.      *
  191.      * @Delete a record from a table
  192.      *
  193.      * @access public
  194.      *
  195.      * @param string $table
  196.      *
  197.      * @param string $fieldname
  198.      *
  199.      * @param string $id
  200.      *
  201.      * @throws PDOexception on failure
  202.      *
  203.      */
  204.     public function dbDelete($table, $fieldname, $id){
  205.         $this->conn();
  206.         $sql  = "DELETE FROM `$table` WHERE `$fieldname` = :id";
  207.         $stmt = $this->db->prepare($sql);
  208.         $stmt->bindParam(':id', $id, PDO::PARAM_STR);
  209.         $stmt->execute();
  210.     }
  211.        
  212.        
  213.         function makePermalink($str, $replace=array(), $delimiter='-') {
  214.             setlocale(LC_ALL, 'en_US.UTF8');   
  215.             if( !empty($replace) ) {
  216.                 $str = str_replace((array)$replace, ' ', $str);
  217.             }
  218.        
  219.             $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
  220.             $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
  221.             $clean = strtolower(trim($clean, '-'));
  222.             $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
  223.        
  224.             return $clean;
  225.         }
  226.  
  227. }
  228. /*** end of class ***/
  229.  
  230. ?>
  231.  
  232. <?php
  233. /*
  234. How to use
  235. */
  236.  
  237.   include 'crud.class.php';
  238.  
  239.     /*** a new crud object ***/
  240.     $crud = new crud();
  241.  
  242.     /*** The DSN ***/
  243.     $crud->dsn = "mysql:dbname=animals;host=localhost";
  244.    
  245.     /*** MySQL username and password ***/
  246.     $crud->username = 'username';
  247.     $crud->password = 'password';
  248.  
  249.  
  250.     /*** array of values to insert ***/
  251.     $values = array(
  252.             array('animal_name'=>'bruce', 'animal_type'=>'dingo'),
  253.             array('animal_name'=>'bruce', 'animal_type'=>'wombat'),
  254.             array('animal_name'=>'bruce', 'animal_type'=>'kiwi'),
  255.             array('animal_name'=>'bruce', 'animal_type'=>'kangaroo')
  256.             );
  257.     /*** insert the array of values ***/
  258.     $crud->dbInsert('animals', $values);
  259.  
  260.     /*** select all records from table ***/
  261.     $records = $crud->rawSelect('SELECT * FROM animals');
  262.  
  263.     /*** fetch only associative array of values ***/
  264.     $rows = $records->fetchAll(PDO::FETCH_ASSOC);
  265.  
  266.     /*** display the records ***/
  267.     foreach($rows as $row)
  268.     {
  269.         foreach($row as $fieldname=>$value)
  270.         {
  271.             echo $fieldname.' = '.$value.'<br />';
  272.         }
  273.         echo '<hr />';
  274.     }
  275.  
  276.     /*** update the kiwi ***/
  277.     $crud->dbUpdate('animals', 'animal_name', 'troy', 'animal_id', 3);
  278.  
  279.     /*** delete the second record ***/
  280.     $res = $crud->dbSelect('animals', 'animal_id', 3 );
  281.  
  282.     /*** show the results ***/
  283.     foreach($res as $row)
  284.     {
  285.         echo $row['animal_name'].' = '.$row['animal_type'].'<br />';
  286.     }
  287. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement