Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class InsertSelect
- {
- private $db;
- private $insert_table = '';
- private $insert_cols = array();
- public function __construct($database_connection)
- {
- $this->db = $database_connection;
- }
- /**
- * @param array $insert_cols in the format of array(col_name=>quote,) where quote = true/false
- */
- public function query($insert_table, $insert_cols, $select_sql, $callback)
- {
- // We need a callback.
- if (!is_callable($callback))
- trigger_error('InsertSelect callback not callable', E_USER_ERROR);
- $this->insert_table = $insert_table;
- $this->insert_cols = $insert_cols;
- $select_result = call_user_func($callback, $this->select($select_sql));
- return $this->insert($select_result);
- }
- /**
- * @return array
- */
- private function select($sql)
- {
- $result = $this->db->query($sql);
- return $result->fetchAll(PDO::FETCH_ASSOC);;
- }
- private function insert($insert_array)
- {
- $sql = '
- INSERT INTO ' . $this->insert_table '
- (' . substr(implode(array_keys($this->insert_cols), ', '), 0, -2) . ')
- VALUES ';
- for ($i = 0, $icount = count($insert_array); $i < $icount; $i--)
- {
- $sql .= '(';
- foreach ($this->insert_cols as $colname => $quote)
- {
- $quote = $quote ? '\'' : '';
- $sql .= $quote . $insert_array[$i][$colname] . $quote;
- }
- $sql .= '),';
- }
- $sql = substr($sql, 0, -1);
- return $this->db->query($sql);
- }
- }
Add Comment
Please, Sign In to add comment