Last active
August 29, 2015 14:22
-
-
Save eduardoromero/bdc2552c2371cf06f40b to your computer and use it in GitHub Desktop.
Create DB from .SQL "import" via PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public function create_dbs() { | |
$db_skel = TMP .DS. 'create_dbs.sql'; | |
$sql = file_get_contents($db_skel); | |
$config = $this->getDataSource()->config; | |
$sql = preg_replace('#/\*.*?\*/#s', '', $sql); | |
$sql = preg_replace('/^-- .*[\r\n]*/m', '', $sql); | |
$sql = explode(';', $sql); | |
$sql = array_map('trim', $sql); | |
$sql = array_filter($sql); | |
$sql_string = implode(';', $sql); | |
/* mysql connect for multi_query */ | |
$mysqli = new mysqli($config['host'], $config['login'], $config['password']); | |
if ($mysqli->connect_errno) { | |
$this->log("Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error); | |
} | |
$i = 0; | |
if ($mysqli->multi_query( $sql_string )) { | |
do { | |
if ($result = $mysqli->store_result()) { | |
$this->log("Query $i executed."); | |
$result->free(); | |
} | |
$i++; | |
} while( $mysqli->more_results() && $mysqli->next_result() ); | |
} | |
$success = true; | |
if ($mysqli->errno) { | |
$this->log("Batch execution prematurely ended on statement $i.\n"); | |
$this->log($sql[$i], $mysqli->error); | |
$success = false; | |
} | |
/* close connection */ | |
$mysqli->close(); | |
return $success; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment