Skip to content

Importing dump from php

diego torres edited this page Dec 11, 2017 · 11 revisions

Snipped from stackoverflow, not tested, but looks nice. Comment if useful!

// https://stackoverflow.com/questions/19751354/how-to-import-sql-file-in-mysql-database-using-php
// http://stackoverflow.com/a/13246630/1050264

$filename = 'churc.sql';
$mysql_host = 'localhost';
$mysql_username = 'root';
$mysql_password = '';
$mysql_database = 'dump';

// Connect to MySQL server
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
// Select database
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());

// Temporary variable, used to store current query
$templine = '';
while (($line = fgets($file)) !== false) { // Loop through each line
    // Skip it if it's a comment
    if (substr($line, 0, 2) == '--' || $line == '')
        continue;

    // Add this line to the current segment
    $templine .= $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
        mysql_query($templine) or print('Error performing query "' . $templine . '":' . mysql_error() . PHP_EOL);
        // Reset temp variable to empty
        $templine = '';
    }
    yield $line;
}
fclose($file);
echo "Tables imported successfully";
Clone this wiki locally