SELECT DISTINCT in CakePHP
Even though CakePHP’s model already includes many of the database query functions, I found that the SELECT DISTINCT was missing. Ok, I know that you can always do it using either Model->query('SELECT DISTINCT `c1`, `c2`) or Model->findAll(null, 'DISTINCT `c1`, `c2`') but that would be like saying use Model->query() instead of Model->findAll().
The cool thing in CakePHP is that you can add your own functions to use in your app on top of the ones that come bundled in the core. For the Model, you just create an ‘app_model.php’ file that you place in our app’s main folder. The empty file should look like this:
/**
* Custom AppModel that adds functionality to the core Model
*/
class AppModel extends Model
{
//empty
}
Now inside your new AppModel class, add the following function:
/**
* Returns a resultset array with DISTINCT fields from database matching given conditions.
*
* @param mixed $conditions SQL conditions as a string or as an array('field' =>'value',...)
* @param mixed $fields Either a single string of a field name, or an array of field names
* @return array Array of records
*/
function findDistinct($conditions = null, $fields = null)
{
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$str = 'DISTINCT ';
if (!is_array($fields))
{
$str .= '`' . $fields . '`';
}
else
{
foreach ($fields as $field)
{
$str .= '`' . $field . '`, ';
}
$str = substr($str, 0, -2);
}
$queryData = array(
'conditions' => $conditions,
'fields' => $str,
);
$data = $db->read($this, $queryData, false);
return $data;
}
You can now use Model->findDistinct('c1') or Model->findDistinct(array('c1', 'c2', 'c3')) to retrieve DISTINCT columns values.
Hoping you find it useful.
nusoap class or SOAP extension?
Back when the web app was to be hosted on the VPS (using PHP4), I had started coding some of the scrapers and parsers to retrieve data from different affiliate networks. After moving to the new servers and setting them up with the latest stable versions of PHP and MySQL, it was time I clean up, optimize and document my code. But no, before I could start doing that and while I was still testing it to refresh my memory on the different methods available within the DtSoap class, I started getting errors!
nusoap
My code required nusoap to communicate with the networks’ WSDL. However, just like for nusoap, PHP5 includes a class named ‘soapclient‘ which caused the conflict. The solution was simple, changing the class’ name to ‘nusoapclient’ and the constructor too before finally changing my code to call for it instead of the old name.
That was the lazy-guy in me reasoning. As soon as the geek kicked in, you guessed it, or maybe not: I decided to update the code and use the built-in soap extension available in PHP5. Continue reading…

