Loading MySQL DB Scheme from PHP
I was creating a web installation for a php/mysql app I wrote and needed to be able to create tables and load data from an sql file. sdeming was able to help me out by providing this script.
The comments in the following scripts will guide you through what is going on.
<? function run_query_batch($handle, $filename="") { // -------------- // Open SQL file. // -------------- if (! ($fd = fopen($filename, "r")) ) { die("Failed to open $filename: " . mysql_error() . "<br>"); } // -------------------------------------- // Iterate through each line in the file. // -------------------------------------- while (!feof($fd)) { // ------------------------- // Read next line from file. // ------------------------- $line = fgets($fd, 32768); $stmt = "$stmt$line"; // ------------------------------------------------------------------- // Semicolon indicates end of statement, keep adding to the statement. // until one is reached. // ------------------------------------------------------------------- if (!preg_match("/;/", $stmt)) { continue; } // ---------------------------------------------- // Remove semicolon and execute entire statement. // ---------------------------------------------- $stmt = preg_replace("/;/", "", $stmt); // ---------------------- // Execute the statement. // ---------------------- mysql_query($stmt, $handle) || die("Query failed: " . mysql_error() . "<br>"); $stmt = ""; } // --------------- // Close SQL file. // --------------- fclose($fd); } run_query_batch($dbhandle, "schema.sql"); ?>
Post new comment