2016-10-15 9 views
0

버튼을 클릭하여 데이터베이스를 다운로드하고 싶습니다. 주변을 검색하고이 코드를 찾았습니다. yii2 database downloadYii2 데이터베이스 다운로드 방법

컨트롤러에 작업을 추가하고이 수정 된 코드를 추가했습니다. 연결을 다시 만들 필요가없는 것으로 생각하여 원래 코드에서 데이터베이스 연결을 제거했습니다. 'fetch_row()'에서 오류가 발생했습니다. Yii::$app->db->createCommand('fetch_row')을 시도했지만 여전히 오류가 발생했습니다. 당신은

// Exploring what tables this database has 
    $result = Yii::$app->db->createCommand('SHOW TABLES'); 

CreateCommand

를 사용하는

하지만 실행하지 않습니다

define('BACKUP_DIR', 'download/') ; 
     // Define Database Credentials 
     define('HOST', 'localhost') ; 
     define('USER', 'root') ; 
     define('PASSWORD', 'x24613rt') ; 
     define('DB_NAME', 'panthoibi') ; 
     $files = scandir(BACKUP_DIR); 
     if(count($files) > 2) { 
      for ($i=2; $i < count($files); $i++) { 
       unlink(BACKUP_DIR."/".$files[$i]); 
      } 
     } 
     /* 
     Define the filename for the sql file 
     If you plan to upload the file to Amazon's S3 service , use only lower-case letters 
     */ 
     $fileName = 'mysqlibackup--' . date('d-m-Y') . '@'.date('h.i.s').'.sql' ; 
     // Set execution time limit 
     if(function_exists('max_execution_time')) { 
      if(ini_get('max_execution_time') > 0)  
       set_time_limit(0) ; 
     } 

     // Check if directory is already created and has the proper permissions 
     if (!file_exists(BACKUP_DIR)) mkdir(BACKUP_DIR , 0700) ; 
     if (!is_writable(BACKUP_DIR)) chmod(BACKUP_DIR , 0700) ; 

     // Create an ".htaccess" file , it will restrict direct accss to the backup-directory . 
     //$content = 'deny from all' ; 
     //$file = new SplFileObject(BACKUP_DIR . '/.htaccess', "w") ; 
     //$file->fwrite($content) ; 


     // Introduction information // 
     $return = ""; 
     $return .= "--\n"; 
     $return .= "-- A mysqli Backup System \n"; 
     $return .= "--\n"; 
     $return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n"; 
     $return = "--\n"; 
     $return .= "-- Database : " . DB_NAME . "\n"; 
     $return .= "--\n"; 
     $return .= "-- --------------------------------------------------\n"; 
     $return .= "-- ---------------------------------------------------\n"; 
     $return .= 'SET AUTOCOMMIT = 0 ;' ."\n" ; 
     $return .= 'SET FOREIGN_KEY_CHECKS=0 ;' ."\n" ; 
     $tables = array() ; 

     // Exploring what tables this database has 
     $result = Yii::$app->db->createCommand('SHOW TABLES'); 

     // Cycle through "$result" and put content into an array 
     while ($row = $result->fetch_row()) 
      $tables[] = $row[0] ; 

     // Cycle through each table 
     foreach($tables as $table) 
     { 
      // Get content of each table 
      $result = $mysqli->query('SELECT * FROM '. $table) ; 
      // Get number of fields (columns) of each table 
      $num_fields = $mysqli->field_count ; 
      // Add table information 
      $return .= "--\n" ; 
      $return .= '-- Tabel structure for table `' . $table . '`' . "\n" ; 
      $return .= "--\n" ; 
      $return.= 'DROP TABLE IF EXISTS `'.$table.'`;' . "\n" ; 
      // Get the table-shema 
      $shema = $mysqli->query('SHOW CREATE TABLE '.$table) ; 
      // Extract table shema 
      $tableshema = $shema->fetch_row() ; 
      // Append table-shema into code 
      $return.= $tableshema[1].";" . "\n\n" ; 
      // Cycle through each table-row 
      while($rowdata = $result->fetch_row()) 
      { 
       // Prepare code that will insert data into table 
       $return .= 'INSERT INTO `'.$table .'` VALUES (' ; 
       // Extract data of each row 
       for($i=0; $i<$num_fields; $i++) 
        $return .= '"'.$rowdata[$i] . "\"," ; 
       // Let's remove the last comma 
       $return = substr("$return", 0, -1) ; 
       $return .= ");" ."\n" ; 
      } 
      $return .= "\n\n" ; 
     } 

     $return .= 'SET FOREIGN_KEY_CHECKS = 1 ; ' . "\n" ; 
     $return .= 'COMMIT ; ' . "\n" ; 
     $return .= 'SET AUTOCOMMIT = 1 ; ' . "\n" ; 
     //$file = file_put_contents($fileName , $return) ; 
     $zip = new ZipArchive() ; 
     $resOpen = $zip->open(BACKUP_DIR . '/' .$fileName.".zip" , ZIPARCHIVE::CREATE) ; 
     if($resOpen) 
      $zip->addFromString($fileName , "$return") ; 
     $zip->close() ; 
     $fileSize = $this->get_file_size_unit(filesize(BACKUP_DIR . "/". $fileName . '.zip')) ; 

답변

0

당신은 mysqli 명령을 YII 쿼리 명령을 혼합하는이 ..

예를 작동하지 않습니다. 너 시도해 봐야 해.

$result = Yii::$app->db->createCommand('SHOW TABLES')->execute(); 

또는

$result = Yii::$app->db->createCommand('SHOW TABLES')->queryOne(); 

또는

$result = Yii::$app->db->createCommand('SHOW TABLES')->queryAll(); 

그런 다음 $ 결과 콘텐츠의 예를 살펴 걸릴 시도 :

var_dump($result); 

귀하의 $ 결과 콘텐츠가

에 대한 적응 될 말아야하지 않습니다를
$result->fetch_row() 

bu 결국 PHP 함수를 사용하여 실제 $ 결과 내용을 반복하거나 관리 할 수 ​​있습니다 ..

+0

'$ result = Yii :: $ app-> db-> createCommand ('SHOW TABLES ') -> execute();' 나는 'var_dump ($ result);'를 추가했다. 결과를보기 위해 다른 모든 것을 제거했습니다. 결과는 'int (23) 1'입니다. 이것은 무엇을 나타내는가? 고맙습니다! – gojiraki

+0

이것은 명령이 실행된다는 것을 의미합니다. (하지만 나는 sql show 명령의 내용을 반환하지 않습니다.) .anyway. 나는 다른 사람의 실행 방법으로 대답을 업데이트했다. – scaisEdge

관련 문제