Execute SQL script from a file using PHP


The code below allows to retrieve and execute all SQL statements defined in a SQL script file removing all comments.

<?php
$sql_file = 'test.sql';

$contents = file_get_contents($sql_file);

// Remove C style and inline comments
$comment_patterns = array('/\/\*.*(\n)*.*(\*\/)?/', //C comments
                          '/\s*--.*\n/', //inline comments start with --
                          '/\s*#.*\n/', //inline comments start with #
                          );
$contents = preg_replace($comment_patterns, "\n", $contents);

//Retrieve sql statements
$statements = explode(";\n", $contents);
$statements = preg_replace("/\s/", ' ', $statements);

require_once 'MDB2.php';

$mdb2 =&amp; MDB2::connect('mysql://usr:pw@localhost/dbnam');

foreach ($statements as $query) {
    if (trim($query) != '') {
        echo 'Executing query: ' . $query . "\n";
        $res =&amp; $mdb2->exec($query);

        if (PEAR::isError($res)) {
            die($res->getMessage());
        }
    }
}
?>

I have used Pear::MDB2 abstraction layer to interact with the database but the code above should work with any other db abstraction layer or PHP built-in functions.

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts
Discovery hosts and services with PHP and Nmap
Ortro 1.3.1 released!

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!