Reading and executing in .sql in PHP

Had a little problem with not being able to read in SQL in from a file and execute it earlier. Solved the problem, turns out php doesnt like executing more than one line of SQL at once so barfs at the ;. So i have exploded the SQL into an array using the ; as the delimeter.

note: this method wont work with commented SQL





<?php
function _read_file($filename)
{
$handle = fopen($filename, 'r');
$theData = fread($handle, filesize($filename));
fclose($handle);
return ($theData);
}
function _dbconnect($config)
{
$link = mysql_connect($config['db']['host'], $config['db']['db_user'], $config['db']['db_password']);
if (!$link) { die('Not connected : ' . mysql_error()); }
$db_selected = mysql_select_db($config['db']['dbname'], $link);
if (!$db_selected) { die ('Can\'t use '.$config['db']['dbname'].' : ' . mysql_error()); }
}
function _dbupdate ($sql)
{
_dbconnect();
$result = mysql_query($sql);
if (!$result) {
die("\n ".'
Invalid query: ' . mysql_error());
}

}

$sql = _read_file( 'some-sql-file.sql', ';');
$sql = explode(';',$sql);
foreach ($sql as $item)
{
if (!empty($item))
{
echo "Executing:
";
echo '
'.$item.'
';
_dbupdate($item);
}
}
?>

Comments

  1. FYI this post is super broken in IE, (6 & 7) but then you should be using Firefox anyway.

    ReplyDelete
  2. FYI this post is super broken in IE, (6 & 7) but then you should be using Firefox anyway.

    ReplyDelete
  3. Firefox Nazi! That said I completely agree.

    ReplyDelete
  4. Firefox Nazi! That said I completely agree.

    ReplyDelete
  5. IE 7 works now must be K2 being a bit great.

    ReplyDelete
  6. IE 7 works now must be K2 being a bit great.

    ReplyDelete

Post a Comment

Popular posts from this blog

The Beer Belly

T-Rextasy