Advertisement
Cast-Bound

SQL Generator

Nov 29th, 2011
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 12.59 KB | None | 0 0
  1. <?
  2.  
  3. require_once("requestme.sql.php");
  4.  
  5. //sample data
  6. $data = array(
  7.     'username' => 'my name' ,
  8.     'password' => '123456' ,
  9.     'email' => 'email@email.com' ,
  10.     'other' => 'other data'
  11. );
  12.  
  13. $injection = <<< EOF
  14. " ' " ' " ' " ' " ' " ' " '''''' " ' OR something
  15. EOF;
  16.  
  17. $sqls = <<< EOF
  18. INSERT INTO users (username,password) ('test' , 'test');
  19. INSERT INTO users (username,password) ('test1' , 'test1');
  20. INSERT INTO users (username,password) ('test2' , 'test2');
  21. INSERT INTO users (username,password) ('test3' , 'test3');
  22. INSERT INTO users (username,password) ('test4' , 'test4');
  23. INSERT INTO users (username,password) ('test5' , 'test5');
  24. UPDATE users SET something = `somewhere` WHERE `wack` = `capcap`;
  25. UPDATE users SET something = `somewhere` WHERE `wack` = `capcap`;
  26. EOF;
  27.  
  28. $sql_file = "test.sql";
  29.  
  30. ?>
  31. <html>
  32. <head>
  33. <style>
  34. PRE {
  35.     border: 1px outset;
  36.     padding-top: 10px;
  37.     padding-bottom: 10px;
  38.     padding-left: 5px;
  39. }
  40. BODY
  41. {
  42.     font-family: tahoma;
  43.     font-size: 13px;
  44. }
  45. </style>
  46. </head>
  47. <body>
  48. <b>SQL Generator</b> Hooray!<br>
  49. Here is a sample data<br>
  50. <pre>
  51. <?print_r($data);?>
  52. </pre><br>
  53.  
  54.  
  55. You can use <b>SQL::insert</b> to generate an <b>INSERT</b> query
  56. <pre>
  57. <?= SQL::insert("users" , $data) ?>
  58. </pre>
  59. Using <b>SQL::update</b> to generate a <b>UPDATE</b> query with or without condition
  60. <pre>
  61. <?= SQL::update("users" , $data , " user_id = " . SQL::quote('my_id')) ?><br>
  62. <?= SQL::update("users" , $data ) ?>
  63. </pre>
  64. and you can also generate <b>REPLACE</b> query with this class using <b>SQL::replace</b> (with UPDATE or INSERT syntax )
  65. <pre>
  66. <?= SQL::replace("users" , $data) ?><br>
  67. <?= SQL::replace("users" , $data , false) ?>
  68. </pre>
  69. even <b>DELETE</b> with <b>SQL::delete</b>
  70. <pre>
  71. <?=SQL::delete('users' , 'user_id = ' . SQL::quote('my_id'))?>
  72. </pre>
  73. Now you can create SQL Time or Datetime easier by using <b>SQL::time</b> and PHP Unix time
  74. <pre>
  75. <?
  76. echo SQL::time(time() , 'DATE') . "<BR>";
  77. echo SQL::time(time() , 'TIME') . "<BR>";
  78. echo SQL::time(time() , 'DATETIME') . "<BR>";
  79. ?>
  80. </pre>
  81. no more SQL injection , everything will be ok ^___^ (<b>SQL::quote</b>)
  82. <pre>
  83. <?=$injection?>
  84.  
  85.  
  86. <b>to</b>
  87.  
  88. <?=SQL::quote($injection)?>
  89. </pre>
  90. render a simple equal condition with <b>SQL::condition</b>
  91. <pre>
  92. <?=SQL::condition(array('my_column' => 'my_data' , 'my_column2' => 'my_data', 'my_column3' => 'data 3'))?><br>
  93. <?=SQL::condition(array('my_column' => 'my_data' , 'my_column2' => 'my_data') , 'OR')?>
  94. </pre>
  95. or simple <b>IN</b> syntax <b>SQL::in</b>
  96. <pre>
  97. <?=SQL::in("my_column" , array('var1' , 'var2' , 'var3'))?>
  98. </pre>
  99.  
  100. and finally , you can split queries to invidual query O__O
  101. <pre>
  102. <?=$sqls?>
  103.  
  104.  
  105. to
  106.  
  107. <?print_r(SQL::split($sqls,false))?>
  108. </pre>
  109. and from sql file :) just using <b>SQL::split</b>
  110. <pre>
  111. <?print_r(SQL::split($sql_file))?>
  112. </pre>
  113. </body>
  114. </html>
  115.  
  116. ------------------------------------------------------------
  117.  
  118. <?
  119.  
  120. class SQL
  121. {
  122.     /**
  123.      * Remove unnecessary string in a sql query
  124.      * @param string $s String 1
  125.      * @param string $s2 String need to be removed
  126.      * @return string
  127.      * @access private
  128.      **/
  129.     function trim($s,$s2) {
  130.         if (substr($s , strlen($s) - strlen($s2)) == $s2) $s = substr($s , 0 , strlen($s) - strlen($s2));
  131.         return $s;
  132.     }
  133.     /**
  134.      * Quote a SQL value
  135.      * @param string $s String need to be quoted
  136.      * @return string
  137.      **/
  138.     function quote($s) {
  139.         return "'".str_replace('\\"', '"', addslashes($s))."'";
  140.     }
  141.     /**
  142.      * Generate SQL Insert Query
  143.      * @param string $table Target table name
  144.      * @param array $data SQL Data  (ColumnName => ColumnValue)
  145.      * @return string
  146.      **/
  147.     function insert($table,$data) {
  148.         if (is_string($data)) {
  149.             return "INSERT INTO $table $data;";
  150.         }
  151.         $field = '';
  152.         $col = '';
  153.         foreach ($data as $k => $v) {
  154.             $field .= "`" . $k . "`,";
  155.             $col .= SQL::quote($v) . ",";
  156.         }
  157.         $field = SQL::trim($field , ',');$col =  SQL::trim($col , ',');
  158.         return "INSERT INTO $table ($field) VALUES ($col);";
  159.     }
  160.     /**
  161.      * Generate SQL Update Query
  162.      * @param string $table Target table name
  163.      * @param array $data SQL Data  (ColumnName => ColumnValue)
  164.      * @param string $cond SQL Condition
  165.      * @return string
  166.      **/
  167.     function update($table,$data,$cond='')
  168.     {
  169.         $sql = "UPDATE $table SET ";
  170.         if (is_string($data)) {
  171.             $sql .= $data;
  172.         } else {
  173.             foreach ($data as $k => $v) {
  174.                 $sql .= "`" . $k . "`" . " = " . SQL::quote($v) . ",";
  175.             }
  176.             $sql = SQL::trim($sql , ',');
  177.         }
  178.         if ($cond != '') $sql .= " WHERE $cond";
  179.         $sql .= ";";
  180.         return $sql;
  181.     }
  182.     /**
  183.      * Generate SQL Delete Query
  184.      * @param string $table Target table name
  185.      * @param string $cond SQL Condition
  186.      * @return string
  187.      **/
  188.     function delete($table,$cond='')
  189.     {
  190.         $sql = "DELETE FROM $table";
  191.         if ($cond != '') $sql .= " WHERE $cond";
  192.         $sql .= ";";
  193.         return $sql;
  194.     }
  195.     /**
  196.      * Generate SQL replace query
  197.      * @param string $table Target table name
  198.      * @param array $data SQL Data (ColumnName => ColumnValue)
  199.      * @param bool $update_sytac Use SET sytac or VALUES ()
  200.      * @return string
  201.      **/
  202.     function replace($table , $data , $update_sytac = true) {
  203.         $sql = "REPLACE $table ";
  204.         if (is_string($data)) {
  205.             $sql .= $data . ";";
  206.             return $sql;
  207.         }
  208.         if ($update_sytac) {
  209.             $sql .= "SET ";
  210.             foreach ($data as $k => $v) {
  211.                 $sql .= "`" . $k . "`" . " = " . SQL::quote($v) . ",";
  212.             }
  213.             $sql = SQL::trim($sql , ',');
  214.             $sql .= ";";
  215.         } else {
  216.             $field = '';
  217.             $col = '';
  218.             foreach ($data as $k => $v) {
  219.                 $field .= "`" . $k . "`" . ",";
  220.                 $col .= SQL::quote($v) . ",";
  221.             }
  222.             $field = SQL::trim($field , ',');$col = SQL::trim($col , ',');
  223.             $sql .="($field) VALUES ($col);";
  224.         }
  225.         return $sql;
  226.     }
  227.     /**
  228.      * Return SQL Time
  229.      * @return string
  230.      **/
  231.     function time($value,$format="DATE") {
  232.         $f = '';
  233.         switch (strtoupper($format)) {
  234.             case 'DATE':
  235.             $f = 'Y-m-d';
  236.             break;
  237.             case 'TIME':
  238.             $f = 'H:i:s';
  239.             break;
  240.             case 'DATETIME':
  241.             default:
  242.             $f = 'Y-m-d H:i:s';
  243.             break;
  244.         }
  245.         return date($f , $value);
  246.     }
  247.     /**
  248.      * Render simple equal condition
  249.      *
  250.      */
  251.     function condition($conditions,$compare='AND')
  252.     {
  253.         foreach ($conditions as $key => $value)
  254.         {
  255.             $conditions[$key] = "`$key` = " . SQL::quote($value);
  256.         }
  257.         $sql = implode(" $compare " , $conditions);
  258.         return $sql;
  259.     }
  260.      
  261.     /**
  262.      * Render simple in syntax
  263.      *
  264.      * @param unknown_type $value
  265.      */
  266.     function in($column,$values)
  267.     {
  268.         $sql = " `$column` IN ";
  269.         if (!is_array($values)) $values = array($values);
  270.         foreach ($values as $key => $value)
  271.         {
  272.             $values[$key] = sql::quote($value);
  273.         }
  274.         return $sql . "(" . implode("," , $values) . ")";
  275.     }
  276.      
  277.     /**
  278.      *  
  279.      *
  280.      * Removes comment and splits large sql files into individual queries
  281.      *
  282.      *
  283.      *
  284.      * @param   string   the sql commands
  285.      * @param    bool    Fetch SQL from file
  286.      * @return  array  sqls
  287.      */
  288.     function split($sql,$file=true) {
  289.         $ret = array();
  290.         if ($file) $sql = implode('' , file($sql));
  291.         $sql = trim($sql);
  292.         $sql_len = strlen($sql);
  293.         $char = '';
  294.             $string_start = '';
  295.             $in_string = false;
  296.      
  297.         for ($i = 0; $i < $sql_len; ++$i) {
  298.             $char = $sql[$i];
  299.      
  300.             // We are in a string, check for not escaped end of
  301.             // strings except for backquotes that can't be escaped
  302.             if ($in_string) {
  303.                 for (;;) {
  304.                     $i = strpos($sql, $string_start, $i);
  305.                     // No end of string found -> add the current
  306.                     // substring to the returned array
  307.                     if (!$i) {
  308.                         $ret[] = $sql;
  309.                         return $ret;
  310.                     }
  311.                     // Backquotes or no backslashes before  
  312.                     // quotes: it's indeed the end of the  
  313.                     // string -> exit the loop
  314.                     else if ($string_start == '`' || $sql[$i-1] != '\\') {
  315.                         $string_start = '';
  316.                         $in_string = false;
  317.                         break;
  318.                     }
  319.                     // one or more Backslashes before the presumed  
  320.                     // end of string...
  321.                     else {
  322.                     // first checks for escaped backslashes
  323.                         $j = 2;
  324.                         $escaped_backslash = false;
  325.                             while ($i-$j > 0 && $sql[$i-$j] == '\\') {
  326.                                 $escaped_backslash = !$escaped_backslash;
  327.                                 $j++;
  328.                             }
  329.                         // ... if escaped backslashes: it's really the  
  330.                         // end of the string -> exit the loop
  331.                         if ($escaped_backslash) {
  332.                             $string_start  = '';
  333.                             $in_string = false;
  334.                             break;
  335.                         }
  336.                         // ... else loop
  337.                         else {
  338.                             $i++;
  339.                         }
  340.                     } // end if...elseif...else
  341.                 } // end for
  342.             } // end if (in string)
  343.             // We are not in a string, first check for delimiter...
  344.             else if ($char == ';') {
  345.                 // if delimiter found, add the parsed part to the returned array
  346.                 $ret[] = substr($sql, 0, $i);
  347.                 $sql = ltrim(substr($sql, min($i + 1, $sql_len)));
  348.                 $sql_len = strlen($sql);
  349.                 if ($sql_len) {
  350.                     $i = -1;
  351.                 } else {
  352.                     // The submited statement(s) end(s) here
  353.                     return $ret;
  354.                 }
  355.             } // end else if (is delimiter)
  356.             // ... then check for start of a string,...
  357.                 else if (($char == '"') || ($char == '\'') || ($char == '`')) {
  358.                 $in_string = true;
  359.                 $string_start = $char;
  360.             } // end else if (is start of string)
  361.      
  362.             // for start of a comment (and remove this comment if found)...
  363.             else if ($char == '#' || ($char == ' ' && $i > 1 && $sql[$i-2] . $sql[$i-1] == '--')) {
  364.                 // starting position of the comment depends on the comment type
  365.                 $start_of_comment = (($sql[$i] == '#') ? $i : $i-2);
  366.                 // if no "\n" exits in the remaining string, checks for "\r"
  367.                 // (Mac eol style)
  368.                 $end_of_comment   = (strpos(' ' . $sql, "\012", $i+2)) ? strpos(' ' . $sql, "\012", $i+2) : strpos(' ' . $sql, "\015", $i+2);
  369.                 if (!$end_of_comment) {
  370.                     // no eol found after '#', add the parsed part to the returned
  371.                     // array and exit
  372.                     // RMV fix for comments at end of file
  373.                     $last = trim(substr($sql, 0, $i-1));
  374.                     if (!empty($last)) {
  375.                         $ret[] = $last;
  376.                     }
  377.                     return $ret;
  378.                 } else {
  379.                     $sql = substr($sql, 0, $start_of_comment) . ltrim(substr($sql, $end_of_comment));
  380.                     $sql_len = strlen($sql);
  381.                     $i--;
  382.                 } // end if...else
  383.             } // end else if (is comment)
  384.         } // end for
  385.      
  386.         // add any rest to the returned array
  387.         if (!empty($sql) && trim($sql) != '') {
  388.             $ret[] = $sql;
  389.         }
  390.         return $ret;
  391.     }
  392. }
  393.  
  394.  
  395.  
  396. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement