PHP code to execute MySQL script

There are advanced and comfortable tools to manage your MySQL databases (i.e.  server side: phpMyAdmin, client side:  SQLyog).

But sometimes you can not use those tools and need the ability to execute some SQL script on server by your own hands, easy and fast way. What to do in such situation? Use this PHP code to execute all SQL commands from SQL script text file, one by one:

$sqlFileToExecute = 'path/to/sql/script.sql';

$hostname = DB_HOST;
$db_name = DB_NAME;
$db_user = DB_USER;
$db_password = DB_PASSWORD;

$link = mysql_connect($hostname, $db_user, $db_password);
if (!$link) {
  die ("MySQL Connection error");
}

mysql_select_db($db_name, $link) or die ("Wrong MySQL Database");

$fp = file($sqlFileToExecute, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$query = '';
foreach ($fp as $line) {
  if ($line != '' && strpos($line, '--') === false) {
  $query .= $line;
    if (substr($query, -1) == ';') {
      mysql_query($query);
      $query = '';
    }
  }
}

Inspire Me :)

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s