PHP: multiple SQL queries in one mysql_query statement

前端 未结 4 1836
死守一世寂寞
死守一世寂寞 2020-11-27 08:45

So I have an SQL dump file that needs to be loaded using mysql_query(). Unfortunately, it\'s not possible to execute multiple queries with it.

-> It cannot be assume

相关标签:
4条回答
  • 2020-11-27 08:50
    <?php
    //STATIC QUERY
    $sql1 = "
    CREATE TABLE tblTable (
    strOne VARCHAR(50) NOT NULL,
    strTwo VARCHAR(50) NOT NULL,
    strThree VARCHAR(50) NOT NULL
    );
    INSERT INTO tblTable
    (strOne, strTwo, strThree)
    VALUES ('String 1', 'String 2', 'String 3');
    UPDATE tblTable
    SET
    strOne = 'String One',
    strTwo = 'String Two'
    WHERE strThree = 'String 3';
    "; 
    //GET FROM FILE
    $sql2 = file_get_contents('dump.sql');
    $queries = preg_split("/;+(?=([^'|^\\\']*['|\\\'][^'|^\\\']*['|\\\'])*[^'|^\\\']*[^'|^\\\']$)/", $sql);
    foreach ($queries as $query){
       if (strlen(trim($query)) > 0) mysql_query($query);
    }
    ?>
    
    0 讨论(0)
  • 2020-11-27 08:54

    Occam's razor strikes again.

    The above explode() function wasn't going to work because there are semicolons in the values. However, what I failed to realize (and mention) is that semicolons always preceed newlines in the SQL dump file. Alas,

    $sql = explode(";\n", file_get_contents('dump.sql'));
    foreach ($sql as $key => $val) {
        mysql_query($val);
    }
    

    Also, thanks for your help, Bill.

    0 讨论(0)
  • 2020-11-27 09:09

    There is a bigger issue here. You might have statements that rely on other statements. You can't just execute them linearly blindly.

    0 讨论(0)
  • 2020-11-27 09:12

    You have more problem cases than just semicolons within strings.

    • Script builtin commands that cannot be executed by mysql_query(), like USE.
    • Statements that are not terminated with a semicolon, like DELIMITER.
    • Statements that contain semicolons, but not inside quotes, like CREATE PROCEDURE.

    I don't know of an easy way to handle this task, without shelling out to the mysql command-line client. I realize you said you can't rely on that client being present, but without that client, you need a large amount of PHP code to parse the script and execute statements appropriately.

    You may be able to find such code inside the phpMyAdmin product. However, that product is licensed under the GPL, so if you use any of the code, you must also license your own project under the GPL.


    See also my answers to these related questions:

    • Running MySQL *.sql files in PHP
    • Loading .sql files from within PHP
    • is it possible to call a sql script from a stored procedure in another sql script?
    0 讨论(0)
提交回复
热议问题