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]);
3

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes I have already edited that with ;\n and here is a second complete solution.
Code fixed, next time give the error message too when a code is failing. Plese less exclamation points.
1

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

2 Comments

I just see the problem: queries contain ; "insert; row1;" so it does not do the trick.
is this query always in this format which means one create table then the rest are insert?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.