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);
}
}
?>
February 11th, 2008 at 1:37 pm
FYI this post is super broken in IE, (6 & 7) but then you should be using Firefox anyway.
February 18th, 2008 at 6:56 am
Firefox Nazi! That said I completely agree.
May 8th, 2008 at 1:51 am
IE 7 works now must be K2 being a bit great.