Archive for November, 2008

Recursively Delete A Non-Empty Directory With PHP5

Posted on November 26th, 2008 in PHP | 1 Comment »

There are bunches of examples on how to delete non-empty directories in PHP but none of the examples that I’ve seen take advantage of PHP5′s RecursiveDirectoryIterator which makes this an almost trivial task. If you haven’t already, please check out the SPL Standard PHP Library Classes. I keep a class of static utility functions and here is my function to delete non-empty directories recursively.

public static function deleteDir($dir) {
    $iterator = new RecursiveDirectoryIterator($dir);
    foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
      if ($file->isDir()) {
         rmdir($file->getPathname());
      } else {
         unlink($file->getPathname());
      }
    }
    rmdir($dir);
}

Please note the RecursiveIteratorIterator::CHILD_FIRST parameter. Without that the listing will not be in the correct order. As you iterate along you will end up trying to delete directories before they are empty. This CHILD_FIRST parameter was added with PHP 5.1 so make sure you have at least that version installed before using this technique.

Zend_Db_Table Not Returning Last Insert Id

Posted on November 3rd, 2008 in PHP, Web Development, Zend Framework | 4 Comments »

I just discovered a significant “gotcha” debugging some code today. Judging from the comments on a variety of blogs and forums I think many of us have had this question. To cut to the chase, if you aren’t getting your last insert id returned when you do a Zend_Db_Table insert, make sure that the array that you are inserting does not have an empty string or a zero set in the primary key field. So, if your primary key column in your database is `id` then this will cause you problems:

//NOTE: $table is an instance of class that extends Zend_Db_Table_Abstract
$data = array('id'=>'', 'color'=>'blue', 'size'=>'large');
$id = $table->insert($data);
echo $id; // --> will print an empty string

If you have to include the name of your primary key column as a key in the array you are tyring to insert, make sure it’s set to null NOT an empty string or zero.

//NOTE: $table is an instance of class that extends Zend_Db_Table_Abstract
$data = array('id'=>null, 'color'=>'blue', 'size'=>'large')'
$id = $table->insert($data);
echo $id; // --> will print the id of the newly inserted row

The reason for this is line 822 in the Zend_Db_Table_Abstract class:

if ($this->_sequence === true && !isset($data[$pkIdentity])) {
  $data[$pkIdentity] = $this->_db->lastInsertId();
}

Notice the isset() condition. If primary key value in the data array you are inserting contains anything other than null then isset() will return true causing the lastInsertId() function to not get called. Hopefully this will clear things up and save us all alot of debugging time!

Get Adobe Flash playerPlugin by wpburn.com wordpress themes