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 =& MDB2::connect('mysql://usr:pw@localhost/dbnam');

foreach ($statements as $query) {
    if (trim($query) != '') {
        echo 'Executing query: ' . $query . "\n";
        $res = $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.

Tags: , ,

  1. Janardhana’s avatar

    where is the require_once ‘MDB2.php’ file

  2. Luca Corbo’s avatar

    The MDB2.php is part of the Pear::MDB2 package. You may download it at the pear.php.net site.

  3. Michael’s avatar

    Fatal error: Call to undefined method MDB2_Error::exec() in DIRECTORY on line 24

    $res = $mdb2->exec($query);

    Any solutions?

  4. mani’s avatar

    where is require_once ‘PEAR.php’; file

  5. mani’s avatar

    Fatal error: Call to undefined method MDB2_Error::exec() in DIRECTORY on line 24

    any solution for this

Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>