 |
| ::: T4VN Statistics ::: |
PHP Scripts : 61 |
PHP Example : 67 |
PHP Tutorials : 21 |
PHP News : 93 |
Total Coupon : 36 |
Other Tutorials : |
Member : 209 |
Visitor Online : 8 |
Today Visit: 399 |
Total Visitor : 262409 |
Most Online : 31 |
|
 |
 |
SQL script import function
Author : Ravi Valmikam
Sometimes you might need a function that imports an entire .sql file into the MySQL database. This function will help you do that.
I have two functions:
1. mysql_import_file : simply imports a file as is
2. mysql_install_db : creates a given DB as well as imports a given SQL file for that DB
| PHP Example : | | <?
/* Accepts a filename and imports the SQL script in it.
Returns: true if all is well
false if something is wrong
(error message is embedded in $errmsg)
One can also use mysql_error() if this function
returns an error.
*/
function mysql_import_file($filename, &$errmsg)
{
/* Read the file */
$lines = file($filename);
if(!$lines)
{
$errmsg = "cannot open file $filename";
return false;
}
$scriptfile = false;
/* Get rid of the comments and form one jumbo line */
foreach($lines as $line)
{
$line = trim($line);
if(!ereg('^--', $line))
{
$scriptfile.=" ".$line;
}
}
if(!$scriptfile)
{
$errmsg = "no text found in $filename";
return false;
}
/* Split the jumbo line into smaller lines */
$queries = explode(';', $scriptfile);
/* Run each line as a query */
foreach($queries as $query)
{
$query = trim($query);
if($query == "") { continue; }
if(!mysql_query($query.';'))
{
$errmsg = "query ".$query." failed";
return false;
}
}
/* All is well */
return true;
}
/* Installs a DB with a given name with the help of a given
.sql file
Returns: true if all is well
false if something is wrong
(error message is embedded in $errmsg)
One can also use mysql_error() if this function
returns an error.
*/
function mysql_install_db($dbname, $dbsqlfile, &$errmsg)
{
$result = true;
if(!mysql_select_db($dbname))
{
$result = mysql_query("CREATE DATABASE $dbname");
if(!$result)
{
$errmsg = "could not create [$dbname] db in mysql";
return false;
}
$result = mysql_select_db($dbname);
}
if(!$result)
{
$errmsg = "could not select [$dbname] database in mysql";
return false;
}
$result = mysql_import_file($dbsqlfile, $errmsg);
return $result;
}
?>
|
Usage Example:
| PHP Example : | | <?
$link = mysql_connect ( "127.0.0.1", "root", "");
if(mysql_install_db("testdb", "testdb.sql", $errmsg))
{
echo "Success!!";
}else
{
echo "failure: ".$errmsg."<br/>".mysql_error();
}
?>
| |
| |

|
 |
| ::: Resources ::: |
|
|
| ::: New Templates ::: |
|
| ::: Other Tutorials ::: |
|
 |