Advertisement
Naohiro19

INSERT Syntax for MySQL

Nov 12th, 2017
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.52 KB | None | 0 0
  1. <?php
  2.  
  3. function insertSql(
  4.             string $table = null,
  5.             array $columns = array(),
  6.             string $priority = null,
  7.             array $partitions = array(),
  8.             array $onDuplicateKeyUpdate = array())
  9. {
  10.     $sql = "INSERT ";
  11.     if (!empty($priority)) {
  12.         if (preg_match('/\A([low]+)\z/i', $priority)) {
  13.             $sql .= 'LOW_PRIORITY ';
  14.         } elseif (preg_match('/\A([delayed]+)\z/i', $priority)) {
  15.             $sql .= 'DELAYED ';
  16.         } elseif (preg_match('/\A([high]+)\z/i', $priority)) {
  17.             $sql .= 'HIGH_PRIORITY ';
  18.         } elseif (preg_match('/\A([ignore]+)\z/i', $priority)) {
  19.             $sql .= 'IGNORE ';
  20.         }
  21.     }
  22.     if (!empty($table)) {
  23.         $sql .= 'INTO '. $table . ' ';
  24.     }
  25.  
  26.     if (!empty($partitions)) {
  27.         $sql .= 'PARTITION (';
  28.         foreach ($partitions as $partition) {
  29.             $sql .= sprintf('`%s`, ', $partition);
  30.         }
  31.         $sql = preg_replace('/,\s$/','', $sql);
  32.         $sql .= ') ';
  33.     }
  34.     if (is_array($columns)) {
  35.         $sql .= 'SET ';
  36.         foreach ($columns as $column => $value) {
  37.             $sql .= sprintf('`%s` = ?, ', $column);
  38.         }
  39.         $sql = preg_replace('/,\s$/','', $sql);
  40.     }
  41.     if (!empty($onDuplicateKeyUpdate)) {
  42.         $sql .= 'ON DUPLICATE KEY UPDATE ';
  43.         foreach ($onDuplicateKeyUpdate as $key => $value) {
  44.             $sql .= sprintf('`%s` = %s, ', $key);
  45.         }
  46.         $sql = preg_replace('/,\s$/','', $sql);
  47.     }
  48.     return $sql;
  49. }
  50. //
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement