1

I want to split SQL in separate queries... but still does not work

$string = 'CREATE TABLE `articles` (
`id` int(9) auto_increment,
`context` text,
PRIMARY KEY (`id`)
) DEFAULT CHARSET='utf8' COLLATE='utf8_general_ci';

INSERT INTO `articles` VALUES (1, "insert; row1;"),
(2, "update; row2;")';


preg_match_all("/([^;\"]*?(\".*?\")?)*?;\s*/U", $string, $result);
print_r($result[0]);
edd
  • 64
  • 8
  • Why split? Just write 2 variables with 2 queries? – Naruto Jan 14 '15 at 08:11
  • Problem solved. Here is the link: http://stackoverflow.com/questions/24423260/split-sql-statements-in-php-on-semicolons-but-not-inside-quotes – edd Jan 16 '15 at 10:53
  • Possible duplicate of [split sql statements in php on semicolons (but not inside quotes)](http://stackoverflow.com/questions/24423260/split-sql-statements-in-php-on-semicolons-but-not-inside-quotes) – mickmackusa Mar 28 '17 at 17:15

3 Answers3

2

Use explode:

$queries = explode(";\n", $string);

Or you can pre-filter the strings:

$strings = array();
function capture($match) {
    global $strings;
    $strings[] = $match[0];
    return '<<<' . count($strings) . '>>>';
}
function recopy($string) {
    global $strings;
    foreach($strings as $key => $value) {
        $string = str_replace('<<<' . $key . '>>>', $value, $string);
    }
    return $string;
}
$string = preg_replace_callback('#([\'"]).*(?<!\\\\)(?:\\\\\\\\)*\\1#isU', 'capture', $string);
$queries = array_map('recopy', explode(";", $string));

And escape ' with \' as says Rasmus.

KyleK
  • 4,643
  • 17
  • 33
1

I think you can use explode(";",$string) or find the ; position then substr()

onegun
  • 803
  • 1
  • 10
  • 27
1

Another issue is that you are using the same ' for both php and the query, instead of wrapping the query in ' try using " instead.

Example: CHARSET='utf8' <-- is using the same sign to tell sql that it's text, but you are allready using that sign to build your query

Epodax
  • 1,828
  • 4
  • 27
  • 32