A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

How to filter database inserts – HTML, Usernames, etc. in Zend Framwork

I woke up today thinking about how to handle strings when inserting to MySQL. What if the string I am trying to save into the database contains HTML characters? Let’s say you are using FCKEditor, how would you “generally” handle strings to be inserted into your database? Because when I think of it, I don’t have a quick answer. I have to test it around until satisfied with the output.

If I am too strict of what to save — then I would have problems outputting the HTML into the browser. Tables would be messed up and form elements would not work.

So, how do you filter different kinds of data to be inserted into MySQL using Zend Framework? Kinds of data as in:

  • Strings with HTML characters (mostly from a CMS form where it needs to render the HTML again)
  • usernames (no special characters)
  • passwords
  • what about encoding?
This entry was posted in General and tagged , , . Bookmark the permalink.

6 Responses to How to filter database inserts – HTML, Usernames, etc. in Zend Framwork

  1. kimbou says:

    ZF has a filter plugin to escape html.

  2. Wenbert says:

    kimbou, can you show a short example?

  3. Roman Nestertsov says:

    To filter incoming data Zend Framework has special kind of classes: Zend_Filter_*. You can find them in the Zend/Filter directory. There are a lot of filters for different situation.
    Below I show you a simple example of using them.

    Zend_Loader::loadClass(‘Zend_Filter_StripTags’);
    // create filter object
    $oF = new Zend_Filter_StripTags();
    // get filtered data from $_POST
    $sSomeText = $oF->filter($this->_request->getPost(‘some_text’));

    In this example we filtered $_POST['some_text'] data with StripTags filter.

  4. Roman Nestertsov says:

    Also with new Zend Framework 1.5 release there are ability to add filters directly to the Form Elements when you use Zend_Form class for automatically filtering incoming data. It’s very usefull method.

  5. Wenbert says:

    Thanks Roman! I have just started Zend_Form a few weeks ago. I started with Akrabat’s Zend_Form Tutorial ( http://akrabat.com/2008/02/21/simple-zend_form-example/ ).

    I love Zend_Form! Especially the “populate”-form and the validators and filters makes my life easier :)

  6. gbaby says:

    i love you

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>