Best practice: Import mySQL file in PHP; split queries

后端 未结 13 616
Happy的楠姐
Happy的楠姐 2020-11-29 00:08

I have a situation where I have to update a web site on a shared hosting provider. The site has a CMS. Uploading the CMS\'s files is pretty straightforward using FTP.

<
13条回答
  •  -上瘾入骨i
    2020-11-29 00:38

    Here is a memory-friendly function that should be able to split a big file in individual queries without needing to open the whole file at once:

    function SplitSQL($file, $delimiter = ';')
    {
        set_time_limit(0);
    
        if (is_file($file) === true)
        {
            $file = fopen($file, 'r');
    
            if (is_resource($file) === true)
            {
                $query = array();
    
                while (feof($file) === false)
                {
                    $query[] = fgets($file);
    
                    if (preg_match('~' . preg_quote($delimiter, '~') . '\s*$~iS', end($query)) === 1)
                    {
                        $query = trim(implode('', $query));
    
                        if (mysql_query($query) === false)
                        {
                            echo '

    ERROR: ' . $query . '

    ' . "\n"; } else { echo '

    SUCCESS: ' . $query . '

    ' . "\n"; } while (ob_get_level() > 0) { ob_end_flush(); } flush(); } if (is_string($query) === true) { $query = array(); } } return fclose($file); } } return false; }

    I tested it on a big phpMyAdmin SQL dump and it worked just fine.


    Some test data:

    CREATE TABLE IF NOT EXISTS "test" (
        "id" INTEGER PRIMARY KEY AUTOINCREMENT,
        "name" TEXT,
        "description" TEXT
    );
    
    BEGIN;
        INSERT INTO "test" ("name", "description")
        VALUES (";;;", "something for you mind; body; soul");
    COMMIT;
    
    UPDATE "test"
        SET "name" = "; "
        WHERE "id" = 1;
    

    And the respective output:

    SUCCESS: CREATE TABLE IF NOT EXISTS "test" ( "id" INTEGER PRIMARY KEY AUTOINCREMENT, "name" TEXT, "description" TEXT );
    SUCCESS: BEGIN;
    SUCCESS: INSERT INTO "test" ("name", "description") VALUES (";;;", "something for you mind; body; soul");
    SUCCESS: COMMIT;
    SUCCESS: UPDATE "test" SET "name" = "; " WHERE "id" = 1;
    

提交回复
热议问题