Archive for March, 2009



Mar 31st

Search for a file and delete it.

This snippet is fairly specific to the task it was required for, a client had a directory on their website that contained literally thousands of folders inside it, not nested just a ton of folders inside of one folder. The task was to search each one of these sub-folders (not recursively to any sub-folders inside these first level ones, just the first level children to the target directory) and search for a file called ‘index.php’ and delete it (the client preferred another file extension be used for the index page).

Think…

-target_directory
   | -subfolder_1
      | -index.html
      | -index.php
   | -subfolder_2
      | -index.html
      | -index.php
   | -subfolder_n
      | -index.html
      | -index.php

// open the target directory
$dh = opendir('/path/to/target/directory');
// iterate through the folders in the target directory
while ( ( $file = readdir($dh) ) !== false )
{
	// only check folders, exclude files and the directory controls
	if ( $file != "." && $file != ".." && !is_file($file) )
	{
		$index_path = $path.'/'.$file.'/'.'index.php';
		// check if 'index.php' exists
		if ( is_file($index_path) )
		{
			// delete 'index.php'
			unlink($index_path);
		}
	}
}
closedir($dh);
Mar 3rd

MySQL copy a row from one table to another.

Recently on a project it became necessary to copy data from one database table to another, identical table. The theory is that once data is data, it is data forever. Meaning this; Just because it isn’t useful information at the moment doesn’t necessarily mean that it will always be useless. Long story short, if you have data… Keep it.

Of course it is possible to just SELECT the data from table_1, INSERT it into table_2 then DELETE the original record from table_1, but why do that when MySQL has built in a shortcut? Enter, the INSERT/SELECT hybrid query.

INSERT INTO table_2
SELECT * FROM table_1 t1
WHERE ( t1.id_field = 'some_unique_id' );

After that, just follow it up with a standard DELETE query to remove the original record.

DELETE FROM table_1
WHERE ( id = 'some_unique_id' );