My Stuff
Username

Password

Articles/Snippets
ASP Classic
C
C#
C++
CSS
HTML
Java
Javascript
MySQL
Perl
PHP
Python
Ruby
Unix/Linux/BSD
VB 6
VB.NET


Loading MySQL DB Scheme from PHP


Your rating: None Average: 5 (1 vote)

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

  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • You can use BBCode tags in the text.
  • You can enable syntax highlighting of source code with the following tags: [code], [blockcode], [asp], [awk], [c], [cpp], [csharp], [drupal5], [drupal6], [java], [javascript], [jquery], [mysql], [perl], [perl6], [php], [python], [ruby], [sql], [vb], [vbnet], [xml].
  • Use to create page breaks.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.