복붙노트

PHP에서 MySQL * .sql 파일 실행하기

PHP

PHP에서 MySQL * .sql 파일 실행하기

새 웹 사이트 데이터베이스를 만들 때 두 개의 * .sql 파일이 있습니다. 첫 번째 파일은 모든 테이블을 만듭니다. 두 번째 파일은 일부 기본 레코드를 채 웁니다. PHP에서이 파일들을 실행하고 싶습니다. 또한 Zend_Framework를 사용하면 도움이 될 것입니다.

추가 정보

해결책

shell_exec () 사용 중 ...

$command = 'mysql'
        . ' --host=' . $vals['db_host']
        . ' --user=' . $vals['db_user']
        . ' --password=' . $vals['db_pass']
        . ' --database=' . $vals['db_name']
        . ' --execute="SOURCE ' . $script_path
;
$output1 = shell_exec($command . '/site_db.sql"');
$output2 = shell_exec($command . '/site_structure.sql"');

... 유용한 출력을 얻지 못했지만 다른 스레드에 대한 몇 가지 제안을 따라 마침내 모든 작업을 완료했습니다. 명령에 --option = value 형식으로 전환하고 <대신에 --execute = "SOURCE ..."를 사용하여 파일을 실행합니다.

또한 shell_exec ()와 exec () 사이의 차이점을 잘 설명하지 못했습니다.

해결법

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

    1.이 질문은 수시로 발생합니다. PHP에서 직접 .sql 스크립트를 실행하는 좋은 해결책은 없습니다. .sql 스크립트에서 일반적인 명령문을 SQL 문으로 실행할 수없는 경우가 있습니다. 예를 들어, mysql 도구는 MySQL 서버에서 인식하지 못하는 명령을 내장하고 있습니다. CONNECT, TEE, STATUS 및 DELIMITER가 있습니다.

    이 질문은 수시로 발생합니다. PHP에서 직접 .sql 스크립트를 실행하는 좋은 해결책은 없습니다. .sql 스크립트에서 일반적인 명령문을 SQL 문으로 실행할 수없는 경우가 있습니다. 예를 들어, mysql 도구는 MySQL 서버에서 인식하지 못하는 명령을 내장하고 있습니다. CONNECT, TEE, STATUS 및 DELIMITER가 있습니다.

    그래서 나는 @ 이그나시오 바스케스 - 에이 브람스의 대답에 +1을 준다. shell_exec ()를 사용하여 mysql 도구를 호출하여 PHP에서 .sql 스크립트를 실행해야한다.

    나는이 테스트가 작동하도록했다.

    $command = "mysql --user={$vals['db_user']} --password='{$vals['db_pass']}' "
     . "-h {$vals['db_host']} -D {$vals['db_name']} < {$script_path}";
    
    $output = shell_exec($command . '/shellexec.sql');
    

    다음과 같은 관련 질문에 대한 답변을 참조하십시오.

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

    2.

    $commands = file_get_contents($location);   
    $this->_connection->multi_query($commands);
    
  3. ==============================

    3.여기 내가 사용하는 것입니다 :

    여기 내가 사용하는 것입니다 :

    function run_sql_file($location){
        //load file
        $commands = file_get_contents($location);
    
        //delete comments
        $lines = explode("\n",$commands);
        $commands = '';
        foreach($lines as $line){
            $line = trim($line);
            if( $line && !startsWith($line,'--') ){
                $commands .= $line . "\n";
            }
        }
    
        //convert to array
        $commands = explode(";", $commands);
    
        //run commands
        $total = $success = 0;
        foreach($commands as $command){
            if(trim($command)){
                $success += (@mysql_query($command)==false ? 0 : 1);
                $total += 1;
            }
        }
    
        //return number of successful queries and total number of queries found
        return array(
            "success" => $success,
            "total" => $total
        );
    }
    
    
    // Here's a startsWith function
    function startsWith($haystack, $needle){
        $length = strlen($needle);
        return (substr($haystack, 0, $length) === $needle);
    }
    
  4. ==============================

    4.이를 위해 전체 SQL 구문 분석기를 만들어야합니다. 대신 mysql 커맨드 라인 도구를 사용하여 PHP에서 외부로 호출하는 것이 좋습니다.

    이를 위해 전체 SQL 구문 분석기를 만들어야합니다. 대신 mysql 커맨드 라인 도구를 사용하여 PHP에서 외부로 호출하는 것이 좋습니다.

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

    5.나는 그것을 사용하지 않았지만 mysqli 클래스는 multi_query 메소드를 가지고있다 :

    나는 그것을 사용하지 않았지만 mysqli 클래스는 multi_query 메소드를 가지고있다 :

    http://php.net/manual/en/mysqli.multi-query.php

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

    6.나는 파티에 꽤 늦었다는 것을 알고 있지만, PHP Mini Admin은 몇 차례의 생명의 은인입니다. 그것은 기본적으로 하나의 파일에 포함 된 "라이트"PHPMyAdmin이므로 복잡한 설치가 필요 없습니다. 그냥 업로드하고 로그인하십시오. Simples!

    나는 파티에 꽤 늦었다는 것을 알고 있지만, PHP Mini Admin은 몇 차례의 생명의 은인입니다. 그것은 기본적으로 하나의 파일에 포함 된 "라이트"PHPMyAdmin이므로 복잡한 설치가 필요 없습니다. 그냥 업로드하고 로그인하십시오. Simples!

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

    7.phpMyAdmin을 잊지 마세요. MySQL과 상호 작용하기위한 아주 견고한 인터페이스.

    phpMyAdmin을 잊지 마세요. MySQL과 상호 작용하기위한 아주 견고한 인터페이스.

    코드에서 직접 상호 작용할 수 있는지 여부를 알 수 없으므로 문제가 해결되는지는 모르겠지만 코드를 직접 버리고 싶습니다.

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

    8.multi_query로 이주 스크립트를 작성했습니다. 그것은 mysql 명령 줄 도구없이 mysqldump 출력과 phpmyadmin 내보내기를 처리 할 수 ​​있습니다. 또한 레일스처럼 DB에 저장된 타임 스탬프를 기반으로 여러 마이그레이션 파일을 처리하는 논리를 만들었습니다. 나는 그것이 더 많은 에러 처리를 필요로하지만 현재 나를 위해 일하는 것을 알고있다.

    multi_query로 이주 스크립트를 작성했습니다. 그것은 mysql 명령 줄 도구없이 mysqldump 출력과 phpmyadmin 내보내기를 처리 할 수 ​​있습니다. 또한 레일스처럼 DB에 저장된 타임 스탬프를 기반으로 여러 마이그레이션 파일을 처리하는 논리를 만들었습니다. 나는 그것이 더 많은 에러 처리를 필요로하지만 현재 나를 위해 일하는 것을 알고있다.

    그것을 확인하십시오 : https://github.com/kepes/php-migration

    개발자 나 수출 도구가 작성한 스크립트 만 사용하여 사용자 입력을 처리하지 않으면 안전하게 사용할 수 있다고 생각합니다.

  9. ==============================

    9.이 스크립트를 사용하여 MySQL 스크립트 파일을 실행할 수 있습니다. 물론 $ hostName, $ userName, $ password, $ dataBaseName, $ port 및 $ fileName을 설정해야합니다.

    이 스크립트를 사용하여 MySQL 스크립트 파일을 실행할 수 있습니다. 물론 $ hostName, $ userName, $ password, $ dataBaseName, $ port 및 $ fileName을 설정해야합니다.

    <?php
    
    function parseScript($script) {
    
      $result = array();
      $delimiter = ';';
      while(strlen($script) && preg_match('/((DELIMITER)[ ]+([^\n\r])|[' . $delimiter . ']|$)/is', $script, $matches, PREG_OFFSET_CAPTURE)) {
        if (count($matches) > 2) {
          $delimiter = $matches[3][0];
          $script = substr($script, $matches[3][1] + 1);
        } else {
          if (strlen($statement = trim(substr($script, 0, $matches[0][1])))) {
            $result[] = $statement;
          }
          $script = substr($script, $matches[0][1] + 1);
        }
      }
    
      return $result;
    
    }
    
    function executeScriptFile($fileName, $dbConnection) {
      $script = file_get_contents($scriptFleName);
      $statements = parseScript($script);
      foreach($statements as $statement) {
        mysqli_query($dbConnection, $statement);
      }
    }
    
    $hostName = '';
    $userName = '';
    $password = '';
    $dataBaseName = '';
    $port = '';
    $fileName = '';
    
    if ($connection = @mysqli_connect($hostName, $userName, $password, $dataBaseName, $port)) {
      executeScriptFile($fileName, $connection);
    } else {
      die('Can not connect to MySQL');
    }
    
  10. ==============================

    10.하나의 제안 :

    하나의 제안 :

    // connect to db.
    if (mysql_query("SOURCE myfile.sql")) {
    
      echo "Hello Sonny";
    
    } 
    
  11. ==============================

    11.응용 프로그램 내에서 테이블 생성을 실행하려면 실행할 때 수행 할 PHP 파일을 작성해야 할 수 있습니다.

    응용 프로그램 내에서 테이블 생성을 실행하려면 실행할 때 수행 할 PHP 파일을 작성해야 할 수 있습니다.

    $hostname  = "localhost";
    $database  = "databasename";
    $username  = "rootuser";
    $UserPassword  = "password";
    
    $myconnection = mysql_pconnect($hostname, $username , $UserPassword) or trigger_error(mysql_error(),E_USER_ERROR); 
    mysql_connect($hostname , $username , $UserPassword ) or die(mysql_error());
    mysql_select_db($database) or die(mysql_error());
    
    if ( !$myconnection ){ echo "Error connecting to database.\n";}
    
    
    $userstableDrop = " DROP TABLE IF EXISTS `users`";
    $userstableCreate = " CREATE TABLE IF NOT EXISTS `users` (
    `UserID` int(11) NOT NULL,
      `User_First_Name` varchar(50) DEFAULT NULL
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15" ;
    
    $userstableInsert = "INSERT INTO `users` (`UserID`, `User_First_Name`) VALUES
    (1, 'Mathew'),
    (2, 'Joseph'),
    (3, 'James'),
    (4, 'Mary')";
    
    $userstableAlter1 = "ALTER TABLE `users` ADD PRIMARY KEY (`UserID`)";
    $userstableAlter2 = " ALTER TABLE `users` MODIFY `UserID` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=15";
    
    $createDb_sql = $userstableDrop;
    $insertSite = mysql_query($createDb_sql);
    
    $createDb_sql = $userstableCreate;
    $insertSite = mysql_query($createDb_sql);
    
    $createDb_sql = $userstableInsert;
    $insertSite = mysql_query($createDb_sql);
    
    $createDb_sql = $userstableAlter1;
    $insertSite = mysql_query($createDb_sql);
    
    $createDb_sql = $userstableAlter2;
    $insertSite = mysql_query($createDb_sql);
    
    echo "Succesful!";
    mysql_close($myconnection );
    
  12. ==============================

    12.다음은 내 솔루션이며 아래 코드는 무엇이 수행되는지 설명합니다. 원칙은 파일을 한 줄씩 읽고 쿼리를 작성하고 각각을 실행하는 것입니다. 나는 "file_get_contents"를 사용하는 많은 솔루션을 보았는데, 좋은 해결책은 아니었다. 왜냐하면 전체 파일 내용을 문자열 변수로 읽어 들이기 때문에 버퍼 문제가 발생할 수 있기 때문이다. 내 솔루션은 TRIGGER의 쿼리도 고려합니다. 배열 할당, 주석 및 빈 줄은 제거됩니다.

    다음은 내 솔루션이며 아래 코드는 무엇이 수행되는지 설명합니다. 원칙은 파일을 한 줄씩 읽고 쿼리를 작성하고 각각을 실행하는 것입니다. 나는 "file_get_contents"를 사용하는 많은 솔루션을 보았는데, 좋은 해결책은 아니었다. 왜냐하면 전체 파일 내용을 문자열 변수로 읽어 들이기 때문에 버퍼 문제가 발생할 수 있기 때문이다. 내 솔루션은 TRIGGER의 쿼리도 고려합니다. 배열 할당, 주석 및 빈 줄은 제거됩니다.

    <?php
     /**
     * Get a connection from database
     * @param type $db_host database hostname
     * @param type $db_user database username
     * @param type $db_password database password
     * @param type $db_name database name
     * @return \PDO
     */
     function get_db_connection($db_host, $db_user, $db_password, $db_name)
    {
        $dns = "mysql:host=$db_host;dbname=$db_name";
        try
        {
            return new PDO($dns, $db_user, $db_password);
        } catch (PDOException $ex)
        {
            return null;
        }
    }
    
    /**
     * Runs SQL queries from file
     */
    
     function exec_sql_queries_from_file($script_file, $db_host, $db_user, $db_password, $db_name)
    {
        // to increase the default PHP execution time
        set_time_limit ( 60 ); // Max time = 60 seconds
    
        // Connect to database
        $connection = get_db_connection($db_host, $db_user, $db_password, $db_name);
    
        // If the connection is acquired
        if($connection != null){
    
            // Open sql file
            $f = fopen($script_file, 'r');
    
            // sql query
            $query = '';
    
            // Default delimiter for queries
            $delimiter = ';';
    
            // read line by line
            while (!feof($f))
            {           
                $line = str_replace(PHP_EOL, '', fgets($f)); // read a line and remove the end of line character
    
                /* if the current line contains the key word 'DELIMITER'. Ex: DELIMITER ;; or DELIMITER $$
                 * mostly used for TRIGGERS' queries
                 */
                if(strpos($line, 'DELIMITER') !== false)
                {
                    // change the delimiter and read the next line
                    $delimiter = str_replace('DELIMITER ', '', $line);
                    continue;
                }   
    
                // Consider the line as part of a query if it's not empty and it's not a comment line
                if (!empty($line) && !starts_with($line, '/*') && !starts_with($line, '--'))
                {
                    // the query hasn't reach its end: concatenate $line to $query if $line is not a delimiter
                    $query .= $line !== $delimiter ? $line : '';
    
                    // if the current line ends with $delimiter: end of current query
                    if (ends_with($line, $delimiter))
                    {                
                        // exec the query
                        $connection->exec($query) or die($connection->errorInfo());
                        // start new query
                        $query = '';
                    }
                }                    
            }
    
            fclose($f);
        }
    }
    
     /**
     * Starts with function
     */
    function starts_with($haystack, $needle)
    {
        return $haystack{0} === $needle{0} ? stripos($haystack, $needle) === 0 : false;
    }
    
    /**
     * Ends with function
     */
    function ends_with($haystack, $needle)
    {
        $pos = stripos($haystack, $needle);
        return $pos === FALSE ? FALSE : substr($haystack, $pos) === $needle;
    

    }

  13. from https://stackoverflow.com/questions/4027769/running-mysql-sql-files-in-php by cc-by-sa and MIT license