Categories
Database PHP Programming

PHP: Importing an SQL file via PHP script

Trying to import an SQL file using PHP? Most people will tell you that using PHP function shell_exec to run the MySQL client is your best bet, but what if you simply can’t do it that way? The solution is quite simple, actually, and doesn’t require programming skills beyond the basic file parsing and query executing.

Importing SQL Files

The following function assumes you already have an SQL connection open, and you’re using the MySQLi extension (which you should be using over the MySQL extension, but that’s discussion for another day).

Here you go:

/*
 * Function to import SQL for a given $file
 */
function import_sql($file, $delimiter = ';') {
	$handle = fopen($file, 'r');
	$sql = '';

	if($handle) {
		/*
		 * Loop through each line and build
		 * the SQL query until it detects the delimiter
		 */
		while(($line = fgets($handle, 4096)) !== false) {
			$sql .= trim(' ' . trim($line));
			if(substr($sql, -strlen($delimiter)) == $delimiter) {
				mysqli_query($sql);
				$sql = '';
			}
		}

		fclose($handle);
	}
}

Leave a Reply

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