Skip to content

Instantly share code, notes, and snippets.

@hnq90
Created February 26, 2016 10:10
Show Gist options
  • Select an option

  • Save hnq90/6afcd540a62173a9b7db to your computer and use it in GitHub Desktop.

Select an option

Save hnq90/6afcd540a62173a9b7db to your computer and use it in GitHub Desktop.
mysql import
<?php
try {
if (! @include_once( './data/install.php' )) {
throw new Exception ('install.php does not exist');
}
if (!file_exists('./data/install.php' )) {
throw new Exception ('install.php does not exist');
} else {
require_once('./data/install.php' );
}
} catch(Exception $e) {
exit('Couldn\'t found data/install.php file.');
}
if (empty($argv[1])) {
exit('Please choose a sql file');
}
$sqlFile = $argv[1];
// Connect to MySQL server
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or exit('Error connecting to MySQL server: ' . mysqli_error());
// Temporary variable, used to store current query
$tmpLine = '';
// Read in entire file
$lines = file($sqlFile);
// Loop through each line
foreach ($lines as $line) {
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '') {
continue;
}
// Add this line to the current segment
$tmpLine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';') {
// Perform the query
mysqli_query($connection, $tmpLine) or print('Error performing query ' . $tmpLine . ': ' . mysqli_error($connection));
// Reset temp variable to empty
$tmpLine = '';
}
}
echo 'Tables imported successfully';
exit(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment