Advertisement
meetsos

Import SQL Database

Apr 22nd, 2017
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.12 KB | None | 0 0
  1. <?php    
  2. // SCRIPT SOURCE: https://github.com/tazotodua/useful-php-scripts/blob/master/import-sql-database-mysql.php
  3. // EXAMPLE: IMPORT_TABLES("localhost","user","pass","db_name", "my_baseeee.sql"); //TABLES WILL BE OVERWRITTEN
  4. // P.S. IMPORTANT NOTE for people who try to change/replace some strings  in SQL FILE before importing, MUST READ:  https://goo.gl/2fZDQL
  5. // https://github.com/tazotodua/useful-php-scripts
  6.  
  7. IMPORT_TABLES("localhost","user","pass","db_name", "file_you_want_to_import.sql");
  8. // ΑΝ ΥΠΑΡΧΟΥΝ ΟΙ ΠΙΝΑΚΕΣ, ΘΑ ΓΙΝΕΙ OVERWRITE. ΑΝ ΔΕΝ ΥΠΑΡΧΟΥΝ ΘΑ ΔΗΜΙΟΥΡΓΗΘΟΥΝ. ΑΝ ΕΙΝΑΙ ΑΔΕΙΟΙ ΘΑ ΓΕΜΙΣΟΥΝ.
  9.  
  10. function IMPORT_TABLES($host,$user,$pass,$dbname, $sql_file_OR_content){
  11.     set_time_limit(3000);
  12.     $SQL_CONTENT = (strlen($sql_file_OR_content) > 300 ?  $sql_file_OR_content : file_get_contents($sql_file_OR_content)  );  
  13.     $allLines = explode("\n",$SQL_CONTENT);
  14.     $mysqli = new mysqli($host, $user, $pass, $dbname); if (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();}
  15.         $zzzzzz = $mysqli->query('SET foreign_key_checks = 0');         preg_match_all("/\nCREATE TABLE(.*?)\`(.*?)\`/si", "\n". $SQL_CONTENT, $target_tables); foreach ($target_tables[2] as $table){$mysqli->query('DROP TABLE IF EXISTS '.$table);}         $zzzzzz = $mysqli->query('SET foreign_key_checks = 1');    $mysqli->query("SET NAMES 'utf8'");  
  16.     $templine = ''; // Temporary variable, used to store current query
  17.     foreach ($allLines as $line)    {                                           // Loop through each line
  18.         if (substr($line, 0, 2) != '--' && $line != '') {$templine .= $line;    // (if it is not a comment..) Add this line to the current segment
  19.             if (substr(trim($line), -1, 1) == ';') {        // If it has a semicolon at the end, it's the end of the query
  20.                 if(!$mysqli->query($templine)){ print('Error performing query \'<strong>' . $templine . '\': ' . $mysqli->error . '<br /><br />');  }  $templine = ''; // set variable to empty, to start picking up the lines after ";"
  21.             }
  22.         }
  23.     }   echo 'Importing finished. Now, Delete the import file.';
  24. }   //see also export.php
  25. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement