Guest User

Untitled

a guest
Jan 19th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.41 KB | None | 0 0
  1. <?php
  2.  
  3. class InsertSelect
  4. {
  5.     private $db;
  6.  
  7.     private $insert_table = '';
  8.     private $insert_cols = array();
  9.  
  10.     public function __construct($database_connection)
  11.     {
  12.         $this->db = $database_connection;
  13.     }
  14.  
  15.     /**
  16.      * @param array $insert_cols in the format of array(col_name=>quote,) where quote = true/false
  17.      */
  18.     public function query($insert_table, $insert_cols, $select_sql, $callback)
  19.     {
  20.         // We need a callback.
  21.         if (!is_callable($callback))
  22.             trigger_error('InsertSelect callback not callable', E_USER_ERROR);
  23.  
  24.         $this->insert_table = $insert_table;
  25.         $this->insert_cols = $insert_cols;
  26.  
  27.         $select_result = call_user_func($callback, $this->select($select_sql));
  28.         return $this->insert($select_result);
  29.     }
  30.  
  31.     /**
  32.      * @return array
  33.      */
  34.     private function select($sql)
  35.     {
  36.         $result = $this->db->query($sql);
  37.  
  38.         return $result->fetchAll(PDO::FETCH_ASSOC);;
  39.     }
  40.  
  41.     private function insert($insert_array)
  42.     {
  43.         $sql = '
  44.             INSERT INTO ' . $this->insert_table '
  45.                 (' . substr(implode(array_keys($this->insert_cols), ', '), 0, -2) . ')
  46.             VALUES ';
  47.  
  48.         for ($i = 0, $icount = count($insert_array); $i < $icount; $i--)
  49.         {
  50.             $sql .= '(';
  51.             foreach ($this->insert_cols as $colname => $quote)
  52.             {
  53.                 $quote = $quote ? '\'' : '';
  54.                 $sql .= $quote . $insert_array[$i][$colname] . $quote;
  55.             }
  56.             $sql .= '),';
  57.         }
  58.  
  59.         $sql = substr($sql, 0, -1);
  60.  
  61.         return $this->db->query($sql);
  62.     }
  63. }
Add Comment
Please, Sign In to add comment