Category: Web development

The joy of a simple SQL query

I was working on an application where I needed all unique brands from a mysql table to populate a HTML select box. I have no idea how to do that quickly with Zend_Table, so I found out you can just pass on your own SQL if you want.

A simple “SELECT DISTINCT brand FROM products ORDER BY brand ASC” will do in these cases. It would even be better if I had a seperate brands table, so I wouldn’t have this problem at all. But since this was a quick and dirty job, there was no brands table ;)

Anyway, these lines will do the job (where $db is an instance of your Db adapter):

$statement = $db->query('SELECT DISTINCT brand FROM products ORDER BY brand ASC');
$this->view->brands = $statement->fetchAll();

Use foreach() in your view to display the list:

echo '


';

And that’s it!

View Helpers vanuit View Helpers aanroepen in Zend Framework

Ik zat vandaag met het volgende probleem:

  1. Er is een view helper (showMenu, te vinden in ‘/library/Sterc/View/Helper/ShowMenu.php’) die een menu genereert vanuit een database
  2. In dat menu moeten url’s worden gegenereerd
  3. Er was in het door mij gemaakte systeem echter al een manier om URL’s te genereren, namelijk een andere view helper (makeUrl)
  4. Probleem: je kan niet even simpel $this->makeUrl() of iets dergelijks aanroepen

Oplossing:

In principe is een view helper gewoon een class. Een class kun je gewoon aanroepen en uitvoeren vanuit bijvoorbeeld de view helper “showMenu”:

Zend_Loader::loadClass('Sterc_View_Helper_MakeUrl');
$url = new Sterc_View_Helper_MakeUrl();
$link = $url->makeUrl($linkId, 'page');

Kleine kanttekening hierbij is: De view helper staat dus hier: ‘/library/Sterc/View/Helper/MakeUrl.php’.

Zo simpel is het dus: 3 regels code, in plaats van de hele functie makeUrl in bijvoorbeeld de view helper ShowMenu te plakken.