Skip to content

Instantly share code, notes, and snippets.

@b4oshany
Created January 9, 2015 05:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save b4oshany/0698d9f32589b77abdcb to your computer and use it in GitHub Desktop.
Save b4oshany/0698d9f32589b77abdcb to your computer and use it in GitHub Desktop.
PHP PDO sql file import.
<?php
namespace libs\mysql;
class PDODbImporter{
private static $keywords = array(
'ALTER', 'CREATE', 'DELETE', 'DROP', 'INSERT',
'REPLACE', 'SELECT', 'SET', 'TRUNCATE', 'UPDATE', 'USE',
'DELIMITER', 'END'
);
/**
* Loads an SQL stream into the database one command at a time.
*
* @params $sqlfile The file containing the mysql-dump data.
* @params $connection Instance of a PDO Connection Object.
* @return boolean Returns true, if SQL was imported successfully.
* @throws Exception
*/
public static function importSQL($sqlfile, $connection)
{
# read file into array
$file = file($sqlfile);
# import file line by line
# and filter (remove) those lines, beginning with an sql comment token
$file = array_filter($file,
create_function('$line',
'return strpos(ltrim($line), "--") !== 0;'));
# and filter (remove) those lines, beginning with an sql notes token
$file = array_filter($file,
create_function('$line',
'return strpos(ltrim($line), "/*") !== 0;'));
$sql = "";
$del_num = false;
foreach($file as $line){
$query = trim($line);
try
{
$delimiter = is_int(strpos($query, "DELIMITER"));
if($delimiter || $del_num){
if($delimiter && !$del_num ){
$sql = "";
$sql = $query."; ";
echo "OK";
echo "<br/>";
echo "---";
echo "<br/>";
$del_num = true;
}else if($delimiter && $del_num){
$sql .= $query." ";
$del_num = false;
echo $sql;
echo "<br/>";
echo "do---do";
echo "<br/>";
$connection->exec($sql);
$sql = "";
}else{
$sql .= $query."; ";
}
}else{
$delimiter = is_int(strpos($query, ";"));
if($delimiter){
$connection->exec("$sql $query");
echo "$sql $query";
echo "<br/>";
echo "---";
echo "<br/>";
$sql = "";
}else{
$sql .= " $query";
}
}
}
catch (\Exception $e)
{
echo $e->getMessage() . "<br /> <p>The sql is: $query</p>";
}
}
}
}
?>
@b4oshany
Copy link
Author

b4oshany commented Jan 9, 2015

It works for the most parts. Only problem I'm having is importing store procedures.

@jcchikikomori
Copy link

Is it okay with PhpMyAdmin dumped sql files??

@MushuLeDragon
Copy link

Great Job ! Works for me. THANKS

@osamaAbdullah
Copy link

Deprecated: Function create_function() is deprecated.

@cinicin
Copy link

cinicin commented Oct 17, 2023

    $file = array_filter($file, function ($line) {
        return strpos(ltrim($line), "--") !== 0;
    });
    $file = array_filter($file, function ($line) {
        return strpos(ltrim($line), "/*") !== 0;
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment