복붙노트

[SQL] PHP 내에서 .SQL 파일로드

SQL

PHP 내에서 .SQL 파일로드

내가 개발 및 PHP 내에서 동적으로 데이터베이스를 만들 필요가있어 것을 응용 프로그램에 대한 설치 스크립트를 만드는거야. 나는 데이터베이스를 만드는 데있어지만 지금은 여러 .SQL 파일에로드해야합니다. 나는 파일과는 mysql_query 그것을 한 번에 라인을 열 계획했던 - 내가 스키마 파일을 보았고, 그들이 라인 당 하나 개의 쿼리 수 없습니다 실현 될 때까지.

(phpMyAdmin을가 수입 명령처럼) 그래서, 내가 어떻게 PHP 내에서 SQL 파일을로드 할 수 있습니까?

해결법

  1. ==============================

    1.나는이 질문에 대답 것 여기 모든 사람들이 사람들이 자신의 서버에 응용 프로그램을 설치할 수있는 웹 응용 프로그램 개발자로 어떤 건지 모르고 있다는 느낌을 받고 있어요. 공유 호스팅, 특히, 당신은 "LOAD DATA"쿼리는 앞서 언급 한 것처럼 SQL을 사용하는 것을 허용하지 않습니다. 대부분의 공유 호스트 또한 shell_exec 사용하는 것을 허용하지 않습니다.

    나는이 질문에 대답 것 여기 모든 사람들이 사람들이 자신의 서버에 응용 프로그램을 설치할 수있는 웹 응용 프로그램 개발자로 어떤 건지 모르고 있다는 느낌을 받고 있어요. 공유 호스팅, 특히, 당신은 "LOAD DATA"쿼리는 앞서 언급 한 것처럼 SQL을 사용하는 것을 허용하지 않습니다. 대부분의 공유 호스트 또한 shell_exec 사용하는 것을 허용하지 않습니다.

    이제, 영업 이익 답변을, 당신의 최선의 방법은 변수에 쿼리를 포함하고 바로 실행할 수있는 PHP 파일을 구축하는 것입니다. 당신이 .SQL 파일을 구문 분석하기로 결정하는 경우에 phpMyAdmin에보고 방법이 .SQL 파일의 데이터를 얻기위한 몇 가지 아이디어를 얻을 수 있습니다. 설치가 다른 웹 응용 프로그램에 주위를보세요 그리고 당신은 오히려 자신의 쿼리에 대한 사용 .SQL 파일보다, 그것을 볼 수 있습니다, 그들은 단지 PHP 파일에 그들을 패키지 단지는 mysql_query를 통해 각 문자열을 실행하거나 그들이 할 필요가 무엇이든 .

  2. ==============================

    2.

    $db = new PDO($dsn, $user, $password);
    
    $sql = file_get_contents('file.sql');
    
    $qr = $db->exec($sql);
    
  3. ==============================

    3.phpBB를 자신의 파일을 구문 분석하는 몇 가지 함수를 사용합니다. 그들은 오히려 (어떤 예외!) 당신은 쉽게 그들이 무엇을 알 수 있도록 (내가 http://www.frihost.com/forums/vt-8194.html에서이 솔루션을 가지고) 잘 주석. 여기에 내가 그것을 많이 사용했습니다 솔루션입니다 :

    phpBB를 자신의 파일을 구문 분석하는 몇 가지 함수를 사용합니다. 그들은 오히려 (어떤 예외!) 당신은 쉽게 그들이 무엇을 알 수 있도록 (내가 http://www.frihost.com/forums/vt-8194.html에서이 솔루션을 가지고) 잘 주석. 여기에 내가 그것을 많이 사용했습니다 솔루션입니다 :

    <php
    ini_set('memory_limit', '5120M');
    set_time_limit ( 0 );
    /***************************************************************************
    *                             sql_parse.php
    *                              -------------------
    *     begin                : Thu May 31, 2001
    *     copyright            : (C) 2001 The phpBB Group
    *     email                : support@phpbb.com
    *
    *     $Id: sql_parse.php,v 1.8 2002/03/18 23:53:12 psotfx Exp $
    *
    ****************************************************************************/
    
    /***************************************************************************
     *
     *   This program is free software; you can redistribute it and/or modify
     *   it under the terms of the GNU General Public License as published by
     *   the Free Software Foundation; either version 2 of the License, or
     *   (at your option) any later version.
     *
     ***************************************************************************/
    
    /***************************************************************************
    *
    *   These functions are mainly for use in the db_utilities under the admin
    *   however in order to make these functions available elsewhere, specifically
    *   in the installation phase of phpBB I have seperated out a couple of
    *   functions into this file.  JLH
    *
    \***************************************************************************/
    
    //
    // remove_comments will strip the sql comment lines out of an uploaded sql file
    // specifically for mssql and postgres type files in the install....
    //
    function remove_comments(&$output)
    {
       $lines = explode("\n", $output);
       $output = "";
    
       // try to keep mem. use down
       $linecount = count($lines);
    
       $in_comment = false;
       for($i = 0; $i &lt; $linecount; $i++)
       {
          if( preg_match("/^\/\*/", preg_quote($lines[$i])) )
          {
             $in_comment = true;
          }
    
          if( !$in_comment )
          {
             $output .= $lines[$i] . "\n";
          }
    
          if( preg_match("/\*\/$/", preg_quote($lines[$i])) )
          {
             $in_comment = false;
          }
       }
    
       unset($lines);
       return $output;
    }
    
    //
    // remove_remarks will strip the sql comment lines out of an uploaded sql file
    //
    function remove_remarks($sql)
    {
       $lines = explode("\n", $sql);
    
       // try to keep mem. use down
       $sql = "";
    
       $linecount = count($lines);
       $output = "";
    
       for ($i = 0; $i &lt; $linecount; $i++)
       {
          if (($i != ($linecount - 1)) || (strlen($lines[$i]) > 0))
          {
             if (isset($lines[$i][0]) && $lines[$i][0] != "#")
             {
                $output .= $lines[$i] . "\n";
             }
             else
             {
                $output .= "\n";
             }
             // Trading a bit of speed for lower mem. use here.
             $lines[$i] = "";
          }
       }
    
       return $output;
    
    }
    
    //
    // split_sql_file will split an uploaded sql file into single sql statements.
    // Note: expects trim() to have already been run on $sql.
    //
    function split_sql_file($sql, $delimiter)
    {
       // Split up our string into "possible" SQL statements.
       $tokens = explode($delimiter, $sql);
    
       // try to save mem.
       $sql = "";
       $output = array();
    
       // we don't actually care about the matches preg gives us.
       $matches = array();
    
       // this is faster than calling count($oktens) every time thru the loop.
       $token_count = count($tokens);
       for ($i = 0; $i &lt; $token_count; $i++)
       {
          // Don't wanna add an empty string as the last thing in the array.
          if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0)))
          {
             // This is the total number of single quotes in the token.
             $total_quotes = preg_match_all("/'/", $tokens[$i], $matches);
             // Counts single quotes that are preceded by an odd number of backslashes,
             // which means they're escaped quotes.
             $escaped_quotes = preg_match_all("/(?&lt;!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$i], $matches);
    
             $unescaped_quotes = $total_quotes - $escaped_quotes;
    
             // If the number of unescaped quotes is even, then the delimiter did NOT occur inside a string literal.
             if (($unescaped_quotes % 2) == 0)
             {
                // It's a complete sql statement.
                $output[] = $tokens[$i];
                // save memory.
                $tokens[$i] = "";
             }
             else
             {
                // incomplete sql statement. keep adding tokens until we have a complete one.
                // $temp will hold what we have so far.
                $temp = $tokens[$i] . $delimiter;
                // save memory..
                $tokens[$i] = "";
    
                // Do we have a complete statement yet?
                $complete_stmt = false;
    
                for ($j = $i + 1; (!$complete_stmt && ($j &lt; $token_count)); $j++)
                {
                   // This is the total number of single quotes in the token.
                   $total_quotes = preg_match_all("/'/", $tokens[$j], $matches);
                   // Counts single quotes that are preceded by an odd number of backslashes,
                   // which means they're escaped quotes.
                   $escaped_quotes = preg_match_all("/(?&lt;!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$j], $matches);
    
                   $unescaped_quotes = $total_quotes - $escaped_quotes;
    
                   if (($unescaped_quotes % 2) == 1)
                   {
                      // odd number of unescaped quotes. In combination with the previous incomplete
                      // statement(s), we now have a complete statement. (2 odds always make an even)
                      $output[] = $temp . $tokens[$j];
    
                      // save memory.
                      $tokens[$j] = "";
                      $temp = "";
    
                      // exit the loop.
                      $complete_stmt = true;
                      // make sure the outer loop continues at the right point.
                      $i = $j;
                   }
                   else
                   {
                      // even number of unescaped quotes. We still don't have a complete statement.
                      // (1 odd and 1 even always make an odd)
                      $temp .= $tokens[$j] . $delimiter;
                      // save memory.
                      $tokens[$j] = "";
                   }
    
                } // for..
             } // else
          }
       }
    
       return $output;
    }
    
    $dbms_schema = 'yourfile.sql';
    
    $sql_query = @fread(@fopen($dbms_schema, 'r'), @filesize($dbms_schema)) or die('problem ');
    $sql_query = remove_remarks($sql_query);
    $sql_query = split_sql_file($sql_query, ';');
    
    $host = 'localhost';
    $user = 'user';
    $pass = 'pass';
    $db = 'database_name';
    
    //In case mysql is deprecated use mysqli functions. 
    mysqli_connect($host,$user,$pass) or die('error connection');
    mysqli_select_db($db) or die('error database selection');
    
    $i=1;
    foreach($sql_query as $sql){
    echo $i++;
    echo "<br />";
    mysql_query($sql) or die('error in query');
    }
    
    ?>
    
  4. ==============================

    4.가장 간단한 솔루션은 입력으로 SQL 스크립트를 사용하여 MySQL의 클라이언트를 실행하는 shell_exec ()를 사용하는 것입니다. 이 포크에 있기 때문에이 느린 조금을 실행할 수 있습니다,하지만 당신은 몇 분에서 코드를 작성하고 뭔가 유용한 작업을 다시 얻을 수 있습니다. PHP 스크립트를 작성하는 것은 어떤 SQL 스크립트가 당신에게 주 걸릴 수 있습니다 실행합니다.

    가장 간단한 솔루션은 입력으로 SQL 스크립트를 사용하여 MySQL의 클라이언트를 실행하는 shell_exec ()를 사용하는 것입니다. 이 포크에 있기 때문에이 느린 조금을 실행할 수 있습니다,하지만 당신은 몇 분에서 코드를 작성하고 뭔가 유용한 작업을 다시 얻을 수 있습니다. PHP 스크립트를 작성하는 것은 어떤 SQL 스크립트가 당신에게 주 걸릴 수 있습니다 실행합니다.

    SQL 스크립트를 지원하면 스크립트가 스크립트의 기능의 하위 집합 만 포함 특정 아니라면 사람들이 여기에 설명하는 것보다 더 복잡하다. 아래는 복잡한이 선으로 줄을 해석하는 스크립트를 코딩 할 수 있도록 일반 SQL 스크립트에 나타날 수있는 몇 가지 예입니다.

    -- Comment lines cannot be prepared as statements
    -- This is a MySQL client tool builtin command.  
    -- It cannot be prepared or executed by server.
    USE testdb;
    
    -- This is a multi-line statement.
    CREATE TABLE foo (
      string VARCHAR(100)
    );
    
    -- This statement is not supported as a prepared statement.
    LOAD DATA INFILE 'datafile.txt' INTO TABLE foo;
    
    -- This statement is not terminated with a semicolon.
    DELIMITER //
    
    -- This multi-line statement contains a semicolon 
    -- but not as the statement terminator.
    CREATE PROCEDURE simpleproc (OUT param1 INT)
    BEGIN
      SELECT COUNT(*) INTO param1 FROM foo;
    END
    // 
    

    당신이 그러한 그 위의 일부 코너의 경우를 제외한 SQL 스크립트의 일부를 지원하는 경우는 파일을 읽고 파일 내에서 SQL 문을 실행하는 PHP 스크립트를 작성하기가 상대적으로 쉽다. 당신이 유효한 SQL 스크립트를 지원하고자한다면, 그것은 훨씬 더 복잡하다.

    이러한 관련 질문도 내 대답을 참조하십시오 :

  5. ==============================

    5.내 프로젝트에서 나는 다음 해결 방법을 사용했습니다 :

    내 프로젝트에서 나는 다음 해결 방법을 사용했습니다 :

    <?php
    
    /**
     * Import SQL from file
     *
     * @param string path to sql file
     */
    function sqlImport($file)
    {
    
        $delimiter = ';';
        $file = fopen($file, 'r');
        $isFirstRow = true;
        $isMultiLineComment = false;
        $sql = '';
    
        while (!feof($file)) {
    
            $row = fgets($file);
    
            // remove BOM for utf-8 encoded file
            if ($isFirstRow) {
                $row = preg_replace('/^\x{EF}\x{BB}\x{BF}/', '', $row);
                $isFirstRow = false;
            }
    
            // 1. ignore empty string and comment row
            if (trim($row) == '' || preg_match('/^\s*(#|--\s)/sUi', $row)) {
                continue;
            }
    
            // 2. clear comments
            $row = trim(clearSQL($row, $isMultiLineComment));
    
            // 3. parse delimiter row
            if (preg_match('/^DELIMITER\s+[^ ]+/sUi', $row)) {
                $delimiter = preg_replace('/^DELIMITER\s+([^ ]+)$/sUi', '$1', $row);
                continue;
            }
    
            // 4. separate sql queries by delimiter
            $offset = 0;
            while (strpos($row, $delimiter, $offset) !== false) {
                $delimiterOffset = strpos($row, $delimiter, $offset);
                if (isQuoted($delimiterOffset, $row)) {
                    $offset = $delimiterOffset + strlen($delimiter);
                } else {
                    $sql = trim($sql . ' ' . trim(substr($row, 0, $delimiterOffset)));
                    query($sql);
    
                    $row = substr($row, $delimiterOffset + strlen($delimiter));
                    $offset = 0;
                    $sql = '';
                }
            }
            $sql = trim($sql . ' ' . $row);
        }
        if (strlen($sql) > 0) {
            query($row);
        }
    
        fclose($file);
    }
    
    /**
     * Remove comments from sql
     *
     * @param string sql
     * @param boolean is multicomment line
     * @return string
     */
    function clearSQL($sql, &$isMultiComment)
    {
        if ($isMultiComment) {
            if (preg_match('#\*/#sUi', $sql)) {
                $sql = preg_replace('#^.*\*/\s*#sUi', '', $sql);
                $isMultiComment = false;
            } else {
                $sql = '';
            }
            if(trim($sql) == ''){
                return $sql;
            }
        }
    
        $offset = 0;
        while (preg_match('{--\s|#|/\*[^!]}sUi', $sql, $matched, PREG_OFFSET_CAPTURE, $offset)) {
            list($comment, $foundOn) = $matched[0];
            if (isQuoted($foundOn, $sql)) {
                $offset = $foundOn + strlen($comment);
            } else {
                if (substr($comment, 0, 2) == '/*') {
                    $closedOn = strpos($sql, '*/', $foundOn);
                    if ($closedOn !== false) {
                        $sql = substr($sql, 0, $foundOn) . substr($sql, $closedOn + 2);
                    } else {
                        $sql = substr($sql, 0, $foundOn);
                        $isMultiComment = true;
                    }
                } else {
                    $sql = substr($sql, 0, $foundOn);
                    break;
                }
            }
        }
        return $sql;
    }
    
    /**
     * Check if "offset" position is quoted
     *
     * @param int $offset
     * @param string $text
     * @return boolean
     */
    function isQuoted($offset, $text)
    {
        if ($offset > strlen($text))
            $offset = strlen($text);
    
        $isQuoted = false;
        for ($i = 0; $i < $offset; $i++) {
            if ($text[$i] == "'")
                $isQuoted = !$isQuoted;
            if ($text[$i] == "\\" && $isQuoted)
                $i++;
        }
        return $isQuoted;
    }
    
    function query($sql)
    {
        global $mysqli;
        //echo '#<strong>SQL CODE TO RUN:</strong><br>' . htmlspecialchars($sql) . ';<br><br>';
        if (!$query = $mysqli->query($sql)) {
            throw new Exception("Cannot execute request to the database {$sql}: " . $mysqli->error);
        }
    }
    
    set_time_limit(0);
    
    $mysqli = new mysqli('localhost', 'root', '', 'test');
    $mysqli->set_charset("utf8");
    
    header('Content-Type: text/html;charset=utf-8');
    sqlImport('import.sql');
    
    echo "Peak MB: ", memory_get_peak_usage(true)/1024/1024;
    

    테스트 SQL 파일 (41MB) 메모리 사용량이 경우 : 3.25Mb

  6. ==============================

    6.mysqli은로 구분 된 여러 쿼리를 실행할 수 있습니다;

    mysqli은로 구분 된 여러 쿼리를 실행할 수 있습니다;

    당신은 전체 파일을 읽고 mysqli_multi_query를 사용하여 한 번에 모두를 실행할 수 ()

    그러나, 나는 이것이 가장 우아한 해결책이 아니라고 첫 번째 수 있습니다.

  7. ==============================

    7.내가 대답에 대해 언급 할 수 없기 때문에, 솔루션 다음 사용주의 :

    내가 대답에 대해 언급 할 수 없기 때문에, 솔루션 다음 사용주의 :

    $db = new PDO($dsn, $user, $password);
    
    $sql = file_get_contents('file.sql');
    
    $qr = $db->exec($sql);
    

    PHP PDO https://bugs.php.net/bug.php?id=61613 버그가 있습니다

    db->exec('SELECT 1; invalidstatement; SELECT 2');
    

    아웃 오류 또는 (PHP 5.5.14에서 테스트)가 false를 반환하지 않습니다.

  8. ==============================

    8.Plahcinski 솔루션의 업데이트 된 솔루션입니다. 또는 당신은 fopen의 더 큰 파일을 FREAD 사용할 수 있습니다 :

    Plahcinski 솔루션의 업데이트 된 솔루션입니다. 또는 당신은 fopen의 더 큰 파일을 FREAD 사용할 수 있습니다 :

    $fp = file('database.sql', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $query = '';
    foreach ($fp as $line) {
        if ($line != '' && strpos($line, '--') === false) {
            $query .= $line;
            if (substr($query, -1) == ';') {
                mysql_query($query);
                $query = '';
            }
        }
    }
    
  9. ==============================

    9.나의 제안 PHPMyBackup의 소스 코드를보고 할 것이다. 그것은 자동 PHP SQL 로더입니다. 당신은 그 상 mysql_query 한 번에 하나 개의 쿼리를로드하고 phpMyAdmin을하고 PHPMyBackup 같은 프로젝트는 이미 SQL을 올바른 방법을 구문 분석의 당신을위한 노력을했을 찾을 수 있습니다. 다시 발명하지 마십시오 그 휠 : P를

    나의 제안 PHPMyBackup의 소스 코드를보고 할 것이다. 그것은 자동 PHP SQL 로더입니다. 당신은 그 상 mysql_query 한 번에 하나 개의 쿼리를로드하고 phpMyAdmin을하고 PHPMyBackup 같은 프로젝트는 이미 SQL을 올바른 방법을 구문 분석의 당신을위한 노력을했을 찾을 수 있습니다. 다시 발명하지 마십시오 그 휠 : P를

  10. ==============================

    10.당신이 확실 그 줄에 해당되지 하나 개의 쿼리? 당신의 텍스트 편집기 포장 라인이 될 수 있지만, 현실에서 각 쿼리는 한 줄에있을 수 있습니다.

    당신이 확실 그 줄에 해당되지 하나 개의 쿼리? 당신의 텍스트 편집기 포장 라인이 될 수 있지만, 현실에서 각 쿼리는 한 줄에있을 수 있습니다.

    어쨌든, 올레의 방법이 가장 좋은 것 같다. 당신이 한 번에 쿼리를 하나를 실행해야하는 이유가있는 경우, 당신은 다음 라인으로 파일 라인을 읽을 구분하기 위해 각 쿼리의 끝에 세미콜론을 사용할 수 있어야합니다. 당신은 훨씬 더는 서버의 메모리에 훨씬 더 친절 할 것 같은 거대한 문자열을 분할하는 것보다 라인으로 파일 라인을 읽는 길 이죠. 예:

    $query  = '';
    $handle = @fopen("/sqlfile.sql", "r");
    
    if ($handle) {
        while (!feof($handle)) {
            $query.= fgets($handle, 4096);
    
            if (substr(rtrim($query), -1) === ';') {
                // ...run your query, then unset the string
                $query = '';
            }
        }
    
        fclose($handle);
    }
    

    물론, 당신은 트랜잭션 및 일괄 처리에서 쿼리의 전체를 많이 실행하는 경우 나머지 부분을 생각해야하지만 아마 새로운 설치 스크립트에 대한 큰 문제가 아니다.

  11. ==============================

    11.Navicat는 덤프에서 작동합니다. 의 첫 번째 / * * / 주석 Navicat를 둔다 덤프해야 할 수도 있습니다.

    Navicat는 덤프에서 작동합니다. 의 첫 번째 / * * / 주석 Navicat를 둔다 덤프해야 할 수도 있습니다.

    $file_content = file('myfile.sql');
    $query = "";
    foreach($file_content as $sql_line){
      if(trim($sql_line) != "" && strpos($sql_line, "--") === false){
        $query .= $sql_line;
        if (substr(rtrim($query), -1) == ';'){
          echo $query;
          $result = mysql_query($query)or die(mysql_error());
          $query = "";
        }
      }
     }
    
  12. ==============================

    12.이 시도:

    이 시도:

    // SQL File
    $SQLFile = 'YourSQLFile.sql';
    
    // Server Name
    $hostname = 'localhost';
    
    // User Name
    $db_user = 'root';
    
    // User Password
    $db_password = '';
    
    // DBName
    $database_name = 'YourDBName';
    
    // Connect MySQL
    $link = mysql_connect($hostname, $db_user, $db_password);
    
    if (!$link) {
    die("MySQL Connection error");
    }
    
    // Select MySQL DB
    mysql_select_db($database_name, $link) or die("Wrong MySQL Database");
    
    // Function For Run Multiple Query From .SQL File
    function MultiQuery($sqlfile, $sqldelimiter = ';') {
    set_time_limit(0);
    
    if (is_file($sqlfile) === true) {
    $sqlfile = fopen($sqlfile, 'r');
    
    if (is_resource($sqlfile) === true) {
    $query = array();
    echo "<table cellspacing='3' cellpadding='3' border='0'>";
    
    while (feof($sqlfile) === false) {
    $query[] = fgets($sqlfile);
    
    if (preg_match('~' . preg_quote($sqldelimiter, '~') . '\s*$~iS', end($query)) === 1) {
    $query = trim(implode('', $query));
    
    if (mysql_query($query) === false) {
    echo '<tr><td>ERROR:</td><td> ' . $query . '</td></tr>';
    } else {
    echo '<tr><td>SUCCESS:</td><td>' . $query . '</td></tr>';
    }
    
    while (ob_get_level() &gt; 0) {
    ob_end_flush();
    }
    
    flush();
    }
    
    if (is_string($query) === true) {
    $query = array();
    }
    }
    echo "</table>";
    
    return fclose($sqlfile);
    }
    }
    
    return false;
    }
    
    /* * * Use Function Like This: ** */
    
    MultiQuery($SQLFile);
    
  13. ==============================

    13.

    mysql_query("LOAD DATA LOCAL INFILE '/path/to/file' INTO TABLE mytable");
    
  14. ==============================

    14.간단히 말해서, 나는이 작업을 수행 한 방법입니다 :

    간단히 말해서, 나는이 작업을 수행 한 방법입니다 :

    쿼리 비동기 mysqli_query 지원을보십시오. 자세한 내용은 여기 : http://php.net/manual/en/mysqli.multi-query.php 여기 https://stackoverflow.com/a/6652908/2002493

  15. ==============================

    15.나는 PostgreSQL의 PDO 드라이버는 세미콜론으로 구분 된 스크립트를 실행하는 것을 허용하지 않는 것으로 나타났습니다. PDO를 사용하여 데이터베이스에 .SQL 파일을 실행하려면이 PHP 코드를 직접의 문을 분할하는 것이 필요하다. 다음 작업에 아주 잘 보이는 솔루션입니다 :

    나는 PostgreSQL의 PDO 드라이버는 세미콜론으로 구분 된 스크립트를 실행하는 것을 허용하지 않는 것으로 나타났습니다. PDO를 사용하여 데이터베이스에 .SQL 파일을 실행하려면이 PHP 코드를 직접의 문을 분할하는 것이 필요하다. 다음 작업에 아주 잘 보이는 솔루션입니다 :

    https://github.com/diontruter/migrate/blob/master/src/Diontruter/Migrate/SqlScriptParser.php

    참조 된 클래스는 데이터베이스 독립적 인 방법으로 나를 위해 트릭을했다, 문제는 제발 내게 메시지가있는 경우. 다음은 프로젝트에 추가 한 후 스크립트를 사용할 수있는 방법입니다 :

    $pdo = new PDO($connectionString, $userName, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $parser = new SqlScriptParser();
    $sqlStatements = $parser->parse($fileName);
    foreach ($sqlStatements as $statement) {
        $distilled = $parser->removeComments($statement);
        if (!empty($distilled)) {
            $statement = $pdo->prepare($sql);
            $affectedRows = $statement->execute();
        }
    }
    
  16. ==============================

    16.당신이 큰 .SQL 파일을 가져올 계획이 아니라면, 단지 메모리에 전체 파일을 읽고, 쿼리로 실행합니다.

    당신이 큰 .SQL 파일을 가져올 계획이 아니라면, 단지 메모리에 전체 파일을 읽고, 쿼리로 실행합니다.

    그것은이었다 내가 사용한 적이 있기 때문에 PHP 동안, 그래서 의사 코드 :

    all_query = read_file("/my/file.sql")
    con = mysql_connect("localhost")
    con.mysql_select_db("mydb")
    con.mysql_query(all_query)
    con.close()
    

    나는 cam8001의 대답에 댓글로 것이다; 파일이 (메가 바이트 이상 말) 거대하지 않는 선에서-A-시간을 실행하거나 시도하고 사용 분할하여 (여러 쿼리로 분할 할 이유가 없습니다 쿼리) 문자열 내에서 세미콜론이있는 경우 휴식 ...

  17. ==============================

    17.이 최고의 코드의 경우는 100 % Goooood을 사용할 수 있습니다 PHP하여 SQL 복원!  많은 감사합니다

    이 최고의 코드의 경우는 100 % Goooood을 사용할 수 있습니다 PHP하여 SQL 복원!  많은 감사합니다

    $file_content = file('myfile.sql');
    $query = "";
    foreach($file_content as $sql_line){
    if(trim($sql_line) != "" && strpos($sql_line, "--") === false){
     $query .= $sql_line;
     if (substr(rtrim($query), -1) == ';'){
       echo $query;
       $result = mysql_query($query)or die(mysql_error());
       $query = "";
      }
     }
    }
    
  18. ==============================

    18.부하와 mysql을 덤프 파일의 구문 분석하면 phpMyAdmin 덤프 가장 쉽고 빠른 방법 ..

    부하와 mysql을 덤프 파일의 구문 분석하면 phpMyAdmin 덤프 가장 쉽고 빠른 방법 ..

    $ mysql -u username -p -h localhost dbname < dumpfile.sql 
    
  19. ==============================

    19.나는 여기에 본 내가 LOAD DATA INFILE에 대한 액세스 권한을 가진 믿을 수없는 서버에 저장 프로 시저를 만드는 동안 구분 기호를 변경할 필요가 처리 한 솔루션 없음. 나는 이미 그것을 알아 내기 위해 phpMyAdmin에 코드를 샅 샅히 뒤져하지 않고이 문제를 해결했던 그 사람을 찾아 기대했다. 다른 사람들과 마찬가지로, 나도 다른 내가 GPL 코드 나 자신을 쓰고 있기 때문에 그 일의 GPL의 방법입니다 사람을 찾는 과정이었다.

    나는 여기에 본 내가 LOAD DATA INFILE에 대한 액세스 권한을 가진 믿을 수없는 서버에 저장 프로 시저를 만드는 동안 구분 기호를 변경할 필요가 처리 한 솔루션 없음. 나는 이미 그것을 알아 내기 위해 phpMyAdmin에 코드를 샅 샅히 뒤져하지 않고이 문제를 해결했던 그 사람을 찾아 기대했다. 다른 사람들과 마찬가지로, 나도 다른 내가 GPL 코드 나 자신을 쓰고 있기 때문에 그 일의 GPL의 방법입니다 사람을 찾는 과정이었다.

  20. ==============================

    20.일부 PHP 라이브러리 ( ";"간단한을 사용하지 않고 자연적으로 폭발) 제대로 폭발, 여러 SQL 문으로 만든 SQL 파일을 구문 분석 할 수 있으며이를 실행합니다.

    일부 PHP 라이브러리 ( ";"간단한을 사용하지 않고 자연적으로 폭발) 제대로 폭발, 여러 SQL 문으로 만든 SQL 파일을 구문 분석 할 수 있으며이를 실행합니다.

    예를 들어, Phing의 PDOSQLExecTask을 확인

  21. ==============================

    21.그냥 모든 사람을위한 문제를 다시 언급합니다 :

    그냥 모든 사람을위한 문제를 다시 언급합니다 :

    PHP의는 mysql_query가 자동으로 각각의 SQL 명령을 끝-구분합니다 및 추가의 설명서에 그렇게 매우 모호합니다. 하나 개의 명령을 넘어 모든 오류를 얻을 것입니다.

    다른는 mysql_query에 SQL 스타일의 주석을 포함하는 문자열, \ n, \ 연구와 괜찮습니다 ..

    는 mysql_query의 제한은 예를 들어, 다음 명령에 직접적으로 위해 SQL 파서가 문제를보고하는 자체를 보여

     You have an error in your SQL syntax; check the manual that corresponds to your
     MySQL server version for the right syntax to use near 'INSERT INTO `outputdb:`
     (`intid`, `entry_id`, `definition`) VALUES...
    

    여기 빠른 솔루션입니다 : (잘 포맷 된 SQL을 가정;

    $sqlCmds = preg_split("/[\n|\t]*;[\n|\t]*[\n|\r]$/", $sqlDump);
    
  22. ==============================

    22.대부분의 호스트는 PHP를 통해 자신의 데이터베이스를 만들 수 없습니다 것입니다,하지만 당신은 것을 해결 한 것 같다. DB를 만든 후에는 조작하고 간단하게 채울 수 있습니다 :

    대부분의 호스트는 PHP를 통해 자신의 데이터베이스를 만들 수 없습니다 것입니다,하지만 당신은 것을 해결 한 것 같다. DB를 만든 후에는 조작하고 간단하게 채울 수 있습니다 :

  23. ==============================

    23.어떤 사람 (Plahcinski)이 코드를 제안 :

    어떤 사람 (Plahcinski)이 코드를 제안 :

    $file_content = file('myfile.sql');
    $query = "";
    foreach($file_content as $sql_line){
      if(trim($sql_line) != "" && strpos($sql_line, "--") === false){
        $query .= $sql_line;
        if (substr(rtrim($query), -1) == ';'){
          echo $query;
          $result = mysql_query($query)or die(mysql_error());
          $query = "";
        }
      }
     }
    

    하지만 난 나를 위해 일한 사람로 업데이트합니다 :

     //selecting my database
        $database = 'databaseTitleInFile';
        $selectDatabase = mysql_select_db($database, $con);
        if(! $selectDatabase )
        {
          die('Could not select the database: ' . mysql_error());
        }
        echo "The database " . $database . " selected successfully\n";
    //reading the file
        $file_path='..\yourPath\to\File';
        if(!file_exists($file_path)){
            echo "File Not Exists";
        }
        $file_content = file_get_contents($file_path);
        $array = explode("\n", $file_content)
    //making queries
        $query = "";
            foreach($array as $sql_line){
    $sql_line=trim($sql_line);
              if($sql_line != "" && substr($sql_line, 0, 2) === "--" && strpos($sql_line, "/*") === false){
                $query .= $sql_line;
                if (substr(rtrim($query), -1) == ';'){
                  $result = mysql_query($query)or die(mysql_error());
                  $query = "";
                }
              }
             }
    

    그것은 더 포괄적이기 때문이다. ;-)

  24. ==============================

    24.이 도움이 될 수 있습니다 ->

    이 도움이 될 수 있습니다 ->

    더 많거나 적은 무엇을하는 일은 첫번째 함수에 주어진 문자열 (당신의 file.sql의 file_get_contents () 값)을 가지고 모든 줄 바꿈을 제거하는 것입니다. 그런 다음하여 데이터를 분할은 ";" 캐릭터. 이 while 루프로 진입이어서, 생성 된 어레이의 각 라인을 찾고. 선이 "`"문자가 포함 된 경우는 쿼리 알고 주어진 라인 데이터에 대한 MYQUERY () 함수를 execture 것입니다.

    암호:

    function myquery($query) {
    
    mysql_connect(dbhost, dbuser, dbpass);
    
    mysql_select_db(dbname);
    
    $result = mysql_query($query);
    
    if (!mysql_errno() && @mysql_num_rows($result) > 0) {
    }
    
    else {
    
    $result="not";
    }
    mysql_close();
    
    return $result;
    
    }
    
    
    
    function mybatchquery ($str) {
    
    $sql = str_replace("\n","",$str)
    
    $sql = explode(";",$str);
    
    $x=0;
    
    while (isset($str[$x])) {
    
    if (preg_match("/(\w|\W)+`(\w|\W)+) {
    
    myquery($str[$x]);
    
    }
    
    $x++
    
    }
    
    return TRUE;
    
    }
    
    
    
    
    function myrows($result) {
    
    $rows = @mysql_num_rows($result);
    
    return $rows;
    }
    
    
    
    
    function myarray($result) {
    
    $array = mysql_fetch_array($result);
    
    return $array;
    }
    
    
    
    
    function myescape($query) {
    
    $escape = mysql_escape_string($query);
    
    return $escape;
    }
    
    
    
    $str = file_get_contents("foo.sql");
    mybatchquery($str);
    
  25. ==============================

    25.나는이 모든 시간을 사용합니다 :

    나는이 모든 시간을 사용합니다 :

    $sql = explode(";",file_get_contents('[your dump file].sql'));// 
    
    foreach($sql as $query)
     mysql_query($query);
    
  26. ==============================

    26.나는 다음과 같은 코드가 꽤 잘 문제를 해결할 수 있기를 바랍니다. 모든 테이블 '내용을 비 웁니다 // $ result_t =는 mysql_query ( "쇼 테이블을"); 동안 ($ 행 = mysql_fetch_assoc ($ result_t)) { 하여 mysql_query (. "TRUNCATE"$ 행 [ 'Tables_in_'$ mysql_database.]); } 현재 쿼리를 저장하는 데 사용 // 임시 변수 $ templine = ''; 전체 파일에서 // 읽기 $ 라인 = 파일 ($ 파일 이름); 각 라인을 통해 // 루프 foreach는 ($ 라인으로 $ 라인) { 이 주석 인 경우에 //를 건너 뛰기 경우 (SUBSTR ($ 선, 0, 2) == '-'|| $ 라인 == '')     계속하다; // 현재 세그먼트에이 줄을 추가 . $ templine = $ 라인; 그것이 끝에 세미콜론이있는 경우 // 조회의 종말 경우 (SUBSTR (트림 ($ 선), -1, 1) == '' ') {     쿼리를 수행 //     는 mysql_query ($ templine) 또는 인쇄 ( '.. $ templine'. '수행 쿼리 \ 오류'의 \ ':'mysql_error를 () '

    '.);     // 재설정 임시 변수 비어 있음     $ templine = ''; } } ?>

    나는 다음과 같은 코드가 꽤 잘 문제를 해결할 수 있기를 바랍니다. 모든 테이블 '내용을 비 웁니다 // $ result_t =는 mysql_query ( "쇼 테이블을"); 동안 ($ 행 = mysql_fetch_assoc ($ result_t)) { 하여 mysql_query (. "TRUNCATE"$ 행 [ 'Tables_in_'$ mysql_database.]); } 현재 쿼리를 저장하는 데 사용 // 임시 변수 $ templine = ''; 전체 파일에서 // 읽기 $ 라인 = 파일 ($ 파일 이름); 각 라인을 통해 // 루프 foreach는 ($ 라인으로 $ 라인) { 이 주석 인 경우에 //를 건너 뛰기 경우 (SUBSTR ($ 선, 0, 2) == '-'|| $ 라인 == '')     계속하다; // 현재 세그먼트에이 줄을 추가 . $ templine = $ 라인; 그것이 끝에 세미콜론이있는 경우 // 조회의 종말 경우 (SUBSTR (트림 ($ 선), -1, 1) == '' ') {     쿼리를 수행 //     는 mysql_query ($ templine) 또는 인쇄 ( '.. $ templine'. '수행 쿼리 \ 오류'의 \ ':'mysql_error를 () '

    '.);     // 재설정 임시 변수 비어 있음     $ templine = ''; } } ?>

  27. ==============================

    27.이 사실은 나를 위해 일한 :

    이 사실은 나를 위해 일한 :

    /* load sql-commands from a sql file */
    function loadSQLFromFile($url)
    {
        // ini_set ( 'memory_limit', '512M' );
        // set_time_limit ( 0 );
    
        global $settings_database_name;
        global $mysqli_object; global $worked; $worked = false;
    
        $sql_query = "";
    
        // read line by line
        $lines = file($url);
        $count = count($lines);
    
        for($i = 0;$i<$count;$i++)
        {
            $line = $lines[$i];
            $cmd3 = substr($line, 0, 3);
            $cmd4 = substr($line, 0, 4);
            $cmd6 = substr($line, 0, 6);
            if($cmd3 == "USE")
            {
                // cut away USE ``;
                $settings_database_name = substr($line, 5, -3);
            }
            else if($cmd4 == "DROP")
            {
                $mysqli_object->query($line); // execute this line
            }
            else if(($cmd6 == "INSERT") || ($cmd6 == "CREATE"))
            {
                // sum all lines up until ; is detected
                $multiline = $line;
                while(!strstr($line, ';'))
                {
                    $i++;
                    $line = $lines[$i];
                    $multiline .= $line;
                }
                $multiline = str_replace("\n", "", $multiline); // remove newlines/linebreaks
                $mysqli_object->query($multiline); // execute this line
            }       
        }
    
        return $worked;
    }
    ?>
    
  28. ==============================

    28.나는 어떤 MySQL의 도구 또는 phpMyAdmin을 내 PHP 응용 프로그램이 다른 호스트의 MySQL 서버에 연결하는 환경을 가지고 있지만 나는 mysqldump를 또는 myadmin 보낸 스크립트를 실행해야합니다. 내가 여기에 언급 한 바와 같이이 문제를 해결하기 위해 나는 스크립트 multi_query를 생성

    나는 어떤 MySQL의 도구 또는 phpMyAdmin을 내 PHP 응용 프로그램이 다른 호스트의 MySQL 서버에 연결하는 환경을 가지고 있지만 나는 mysqldump를 또는 myadmin 보낸 스크립트를 실행해야합니다. 내가 여기에 언급 한 바와 같이이 문제를 해결하기 위해 나는 스크립트 multi_query를 생성

    그것은 MySQL의 명령 줄 도구없이 mysqldump는 출력과 phpMyAdmin에 수출을 처리 할 수 ​​있습니다. 또한 레일과 같은 DB에 저장된 타임 스탬프에 따라 여러 마이그레이션 파일을 처리하기 위해 몇 가지 논리를했다. 나는 더 많은 오류 처리를 필요로하지만, 현재 나를 위해 작업을 수행 알고있다.

    그것을 체크 아웃 : https://github.com/kepes/php-migration

    그것은 순수한 PHP의 어떤 다른 도구가 필요하지 않습니다. 당신은 개발자 또는 안전하게 사용할 수 있습니다 수출 도구를 사용하여 만든 스크립트 만 사용자의 입력을 처리하지 않는 경우.

  29. ==============================

    29.이것은 내가 일하고 프로젝트에서입니다. 의견과 불필요한 줄 바꿈을 무시하고 기본적으로 SQL 문을 텍스트 파일을 소요하고 추출합니다.

    이것은 내가 일하고 프로젝트에서입니다. 의견과 불필요한 줄 바꿈을 무시하고 기본적으로 SQL 문을 텍스트 파일을 소요하고 추출합니다.

    <?php
    
      /*
         ingestSql(string) : string
    
         Read the contents of a SQL batch file, stripping away comments and
         joining statements that are broken over multiple lines with the goal
         of producing lines of sql statements that can be successfully executed
         by PDO exec() or execute() functions.
    
         For example:
           -- My SQL Batch
           CREATE TABLE foo(
             bar VARCHAR(80),
             baz INT NOT NULL);
    
         Becomes:
           CREATE TABLE foo(bar VARCHAR(80), baz INT NOT NULL);
      */
    
      function ingestSql($sqlFilePath=__DIR__ . "/create-db.sql") {
        $sqlFile = file($sqlFilePath);
        $ingestedSql = "";
         $statement = "";
        foreach($sqlFile as $line) {
    
          // Ignore anything between a double-dash and the end of the line.
          $commentStart = strpos($line, "--");
          if ($commentStart !== false) {
            $line = substr($line, 0, $commentStart);
          }
    
          // Only process non-blank lines.
          if (strlen($line)) {
    
            // Remove any leading and trailing whitespace and append what's
            // left of the line to the current statement.
            $line = trim($line);
            $statement .= $line;
    
            // A semi-colon ends the current statement.  Otherwise what was a
            // newline becomes a single space;
            if (substr($statement, -1) == ";") {
              $ingestedSql .= $statement;
              $statement = "\n";
            }
            else {
              $statement .= " ";
            }
          }
        }
    
        return $ingestedSql;
      }
    
    ?>
    
  30. from https://stackoverflow.com/questions/147821/loading-sql-files-from-within-php by cc-by-sa and MIT license