PHP code to execute MySQL script



There are advanced and comfortable tools to manage your MySQL databases. For example:

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 = 'sqlscript.sql';
$hostname = '';
$db_user = 'dbuser';
$db_password = 'dbpassword';
$link = mysql_connect($hostname, $db_user, $db_password);
if (!$link) {
  die ("MySQL Connection error");
$database_name = 'databasename';
mysql_select_db($database_name, $link) or die ("Wrong MySQL Database");
// read the sql file
$f = fopen($sqlFileToExecute,"r+");
$sqlFile = fread($f, filesize($sqlFileToExecute));
$sqlArray = explode(';',$sqlFile);
foreach ($sqlArray as $stmt) {
  if (strlen($stmt)>3 && substr(ltrim($stmt),0,2)!='/*') {
    $result = mysql_query($stmt);
    if (!$result) {
      $sqlErrorCode = mysql_errno();
      $sqlErrorText = mysql_error();
      $sqlStmt = $stmt;
if ($sqlErrorCode == 0) {
  echo "Script is executed succesfully!";
} else {
  echo "An error occured during installation!<br/>";
  echo "Error code: $sqlErrorCode<br/>";
  echo "Error text: $sqlErrorText<br/>";
  echo "Statement:<br/> $sqlStmt<br/>";

You can download this script here

Tags: , , ,

  • Luhfluh

    Very useful script tool, thanks a bunch!!

  • Thanks 🙂 very helpfull

  • alariva

    Seems to be good!
    What about semicolon char in data fields ?

  • George Wood

    Many Thanks.

    This got me moving forward after many hours of frustration.