<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tortoise IT &#187; Php Exec</title>
	<atom:link href="http://www.sean-barton.co.uk/tag/php-exec/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sean-barton.co.uk</link>
	<description>by Sean Barton, a freelance PHP website developer in Crewe, Cheshire</description>
	<lastBuildDate>Tue, 31 Jan 2012 17:34:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>SQL Import from a file using PHP</title>
		<link>http://www.sean-barton.co.uk/2009/03/sql-import-from-a-file-using-php/</link>
		<comments>http://www.sean-barton.co.uk/2009/03/sql-import-from-a-file-using-php/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 14:16:09 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[Time Savers]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Wordpress]]></category>
		<category><![CDATA[Mysql Import]]></category>
		<category><![CDATA[Php Exec]]></category>
		<category><![CDATA[Security Issues]]></category>
		<category><![CDATA[Software Installation]]></category>

		<guid isPermaLink="false">http://www.sean-barton.co.uk/?p=220</guid>
		<description><![CDATA[On seeing the title of this post your first uncontrollable outburst may be &#8216;Why on earth would I want to do that?&#8216;. On further reading, you may decide that PHP is the way to get tables created from within an automated install process (WordPress plugin activation or PHP based software &#8216;installation&#8217;). It may trigger another outburst when you see that the code I am about to paste in is more than a single line long (which would be all it would take using the PHP exec() command). Why not use the Exec command? Alot of developers cringe at the thought &#8230; <a class="continue_reading" href="http://www.sean-barton.co.uk/2009/03/sql-import-from-a-file-using-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>On seeing the title of this post your first uncontrollable outburst may be &#8216;<em>Why on earth would I want to do that?</em>&#8216;. On further reading, you may decide that PHP is the way to get tables created from within an automated install process (WordPress plugin activation or PHP based software &#8216;installation&#8217;). It may trigger another outburst when you see that the code I am about to paste in is more than a single line long (which would be all it would take using the PHP exec() command).</p>
<p><strong>Why not use the Exec command?</strong></p>
<p>Alot of developers cringe at the thought of the exec command in PHP, others have disabled it due to &#8216;security issues&#8217;. My reason for not using it is because my script doesnt just import SQL. It can do two very important things for me:</p>
<ul>
<li>Prioritise the import</li>
<li>Prefix the table names</li>
</ul>
<p>Prioritising the import isn&#8217;t essential but it means that your SQL file can be a mess of random statements and no matter where the INSERTs are, they will be grouped and run last to allow the CREATE statements a chance to work.</p>
<p>Prefixing the table names is almost self explanatory. Wordress, which I wrote this script for, allows Database prefixes to be used when setting up a blog. It only makes sense that to avoid conflict when more than one blog is in the same database to prefix my tables with the same string.</p>
<p><strong>How does it all work?</strong></p>
<p>For those interested the code above simply does the following:</p>
<ul>
<li>Imports the file from an absolute path passed to the function into an array split by line</li>
<li>Loops through the lines looking for starting words defined as SQL statement keywords in an array and generates a list of complete statements</li>
<li>Removes all comments as it goes (comment defined as any line starting with &#8216;&#8211;&#8217;</li>
<li>Looks for the first backtick character (`) which MUST be present (at least around the table name) and inserts the WordPress Database Prefix</li>
<li>Inserts the completed query into an array grouped by those that are INSERT queries and those that aren&#8217;t</li>
<li>Sorts the new array by a priority figure (new numbers can be added to mark muti-level priority if you like)</li>
<li>Runs the queries</li>
</ul>
<p><strong>Integration</strong></p>
<p>To integrate it into your WordPress plugin then simply copy/paste the code into yours and pass it an absolute path on plugin activation. I also use it to drop tables on a &#8216;hard&#8217; deactivation by passing it an SQL file full of DROP commands. To integrate it into your NON WordPress site then simply remove all references to $wpdb and substitute &#8216;$wpdb-&gt;prefix&#8217; with your own string or variable name.</p>
<p><strong>The Code</strong></p>
<p>Here is the code although I have also provided it in download form: <a class="downloadlink" href="http://www.sean-barton.co.uk/wp-content/plugins/download-monitor/download.php?id=8" title="Version 0.1 downloaded 2408 times" >MySQL Import Script (1.14 kB)</a></p>
<p><em></em></p>
<pre>function mysql_import($filename) {
	global $wpdb;

	$return = false;
	$sql_start = array('INSERT', 'UPDATE', 'DELETE', 'DROP', 'GRANT', 'REVOKE', 'CREATE', 'ALTER');
	$sql_run_last = array('INSERT');

	if (file_exists($filename)) {
		$lines = file($filename);
		$queries = array();
		$query = '';

		if (is_array($lines)) {
			foreach ($lines as $line) {
				$line = trim($line);

				if(!preg_match("'^--'", $line)) {
					if (!trim($line)) {
						if ($query != '') {
							$first_word = trim(strtoupper(substr($query, 0, strpos($query, ' '))));
							if (in_array($first_word, $sql_start)) {
								$pos = strpos($query, '`')+1;
								$query = substr($query, 0, $pos) . $wpdb-&gt;prefix . substr($query, $pos);
							}

							$priority = 1;
							if (in_array($first_word, $sql_run_last)) {
								$priority = 10;
							} 

							$queries[$priority][] = $query;
							$query = '';
						}
					} else {
						$query .= $line;
					}
				}
			}

			ksort($queries);

			foreach ($queries as $priority=&gt;$to_run) {
				foreach ($to_run as $i=&gt;$sql) {
					$wpdb-&gt;query($sql);
				}
			}
		}
	}
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.sean-barton.co.uk/2009/03/sql-import-from-a-file-using-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk
Page Caching using disk (enhanced)
Database Caching 8/22 queries in 0.055 seconds using disk
Object Caching 336/348 objects using disk

Served from: www.sean-barton.co.uk @ 2012-02-08 22:14:01 -->
