Check your SQL file before use

I have php code that I am using to import a .sql file into a mysql database. The first thing the code does is check the file and if it exists then it drops multiple tables and imports the sql file (replacing the dropped tables). As you can imagine, once the sql file was invalid, but the code went through and dropped the tables. Is there a way to check the validity of a sql file using php?

This requires some kind of automation for several reasons. I don't always do imports. Once imported, the code immediately uses the new tables to update / create / delete records in other tables. Therefore, I cannot have a workflow when I stop the process to check if it was successful; I need a way to test php for success.

This is the code used to import the sql file:

$templine = '';  
$lines = file($filename);  
foreach ($lines as $line) {  
    if (substr($line, 0, 2) == '--' || $line == '') continue;  
    $templine .= $line;  
    if (substr(trim($line), -1, 1) == ';') {  
        $wpdb->query($templine);  
        $templine = '';  
    }  
}  

      

+3


source to share


1 answer


Interesting. I can think of two ways.

One approach is to have an alternate database to use as a test, connect to this database, import sql into this database first, test it with the query. If this passes, then connect to the main database and proceed as usual.



Another approach is to export the existing database to sql file. After importing the sql file, check if it works with the query, if not, import the old database with the exported sql file.

All of this can be automated to run in 1 step.

0


source







All Articles