Menu Search
Jump to the content X

Ask SM [PHP]: Form Validation, Converting MySQL to XML


By Jason Lengstorf

PHP and other server-side programming languages are tricky. The manual can be tough to decipher, and there isn’t really a way to “validate” a PHP script. If you’re new to programming, you may lost and not know where to look for help. When I first started programming, I spent hours pulling my hair out, digging through manuals, and poring over books. It wasn’t until I found a great online community that I really started to get in the swing with PHP and felt like I was actually accomplishing something.

Here at Smashing Magazine, we want to help out PHP programmers who are just getting started or who want to improve their programming chops. Our goal is to support our community by answering their questions and trying to find solutions to their problems.

While Chris Coyier takes care of CSS and JavaScript-related questions, from now on me, Jason Lengstorf, will take care of your PHP- and MySQL-related questions.


You can just tweet me @jasonatennui with the tag “[Ask SM].” In our first installment, we’ll answer a smattering of user-submitted questions about PHP and MySQL. Posts focused on Ruby, Python, Photoshop and Illustrator are coming as well.

1. Form validation with PHP Link

@titel asks:

What is an easy-to-implement and reusable set of functions or small class that automates form validation with PHP?

I’ve heard good things about this form validation class, but I think it’s really better to take the time to write your own. There are tons of easy tutorials on Google to get you started; and as your needs change, you’ll probably end up tweaking the code to fit your needs.

If you’re going to be storing the validated values in a MySQL database, it would be wise to look into methods of avoiding injection attacks. There are some wonderful free libraries (mysqli and PDO, for instance) that go a long ways towards securing your Web applications by creating prepared statements that help prevent SQL injection.

2. Converting MySQL to XML Link

@igmuska asks:

What’s the best practice for converting MySQL to XML for using Google Maps on a PHP page?

There’s a pretty good tutorial on the Google Maps API page to get familiar with the format that you’ll need to use for the XML file, and then you’ll want to write a function or class to handle the creation of individual XML entries.

You could do something like this to generate your XML output:

while($entry = mysql_fetch_assoc($result)) {
  $xml .= <<<XML_OUTPUT
  <point lng="{$entry['longitude']}" lat="{$entry['latitude']}" />
  <icon image="{$entry['icon']}" class="local" />

3. require_once()-problem Link

@DanBowles asks:

I performed a require_once(…) on a config file only to find I could not access the variables in the file. How come?

There’s no hard and fast answer to that question, but possible problems could be that you’re trying to access variables inside a function without declaring them as globals, or that your config file is in a format that your server isn’t configured for to parse PHP.

To make sure the PHP in the config file is being parsed, make the file output some text (i.e. echo ‘Is this thing on?’;) and see if it shows up when you require the file. If you’re trying to use variables from the config file in a function contained in the parent file, declare the variable as a global at the top of the function (i.e. global $myVar;).

4. Search in different tables? Link

@MikevHoenselaar asks:

What is the best way to search a website with MySQL/PHP in different tables?

To search multiple tables, start by using JOIN in your MySQL query. A great introductory article on the concept is available here. With regard to the best method of searching, that depends on the type of information you’re searching for.

If you’re looking for an exact phrase, it’s probably best to start off with a LIKE-statement, which looks for an exact word or phrase (i.e. a search of entry titles). More general queries would best be handled by a fulltext-search, which runs through a table and finds relevant entries (i.e. a site-wide search for entries related to a cetain word or phrase).

5. Getting information out of an XML-file Link

@korteev asks:

How can I get information out of an XML file?

RSS is an extremely useful tool for developers because it allows us to take information from one website and put it in another. It also has the benefit of allowing you to format that content fairly easily.

For PHP5, SimpleXML is a great tool that makes parsing XML feeds really easy. There’s a great article here on how to use it, as well as a resource on that reviews the different methods available.

After you get the hang of it, using it is pretty straightforward. For example, take this XML file:

<?xml version="1.0"?>
      <name>John Doe</name>
      <name>Jane Doe</name>

To get information out of the file, all we have to do is this:

  $people = simplexml_load_file('people.xml');
  foreach ($people->person as $person) {
      echo "Name: {$person['name']}n";
      echo "Age: {$person['age']}n";

SimpleXML also supports namespaces, which is very useful when parsing Flickr’s RSS feed, for example.

Further Resources Link

  • PHP Manual — This is my bible.
  • MySQL Manual — A little harder to understand, but still incredibly useful.
  • W3Schools Forum — When I get stuck, I can always count on these guys for help.


Smashing Book #5

Hold on tiger! Thank you for reading the article. Did you know that we also publish printed books and run friendly conferences – crafted for pros like you? For example, Smashing Book 5, packed with smart responsive design patterns and techniques.

↑ Back to top Tweet itShare on Facebook

Jason Lengstorf is a 23-year-old software designer and developer based in Missoula, MT. As the owner of Ennui Design, he specializes in creating custom Web applications, ranging from simple informational websites to full-fledged content management systems. When not glued to his keyboard, he’s likely standing in line for coffee, shopping for cowboy shirts, or pretending to know something about wine.

  1. 1

    The form validation example given leads to Clonefish, which is an eyesore to be blunt. Try – much better.

  2. 2

    Nice. Handy lil tips there

  3. 3

    I just started to code in php and I know this will come in handy. Thanks!

  4. 4

    required_once( )- problem
    Good tips

  5. 5

    the require|include[_once] issue is generally caused by the way or depth it’s called in. one page with a bunch of requires has access to all the variables inside them. if require is called within a function, i believe only that function retains access to those variables (without using global $var of course).
    annoying if you don’t realize why it’s happening, for sure.

  6. 6

    Thanks for adding that. Great point!

  7. 7

    Many time it’s just a Headache when you run the script and you got more the 500 errors . Always the first thought is obviously about the new PHP upgradation. Many time i too got into same problems. IN my case i found the problem in ‘required_once’ statement as the php script included by the ‘required_once’ is executing however there is no variables set in the included script are being passed back to the including script.

    Thanks Jason for nice Article.

    DKumar M.

  8. 8


  9. 9

    Wow, I’m blown away. That’s some serious expert level programming there. phew. I love the types of “programmers” that exist these days, due to the inherit idiocy in PHP development.

  10. 10

    @DKumar, yea you just have to be aware of the context in which the require was called. when in doubt use global $varName and it will give access, but it’s nice to use require in such a way that you don’t have to `global` things.

    @mikemike, some say PHP is “too easy” to program in, causing seriously bad scripts and errors for the masses. meh.

  11. 11

    PHP does have a “validation” of sorts; it’s called error reporting, and it is your friend. It tells you everything you need to know about why your script isn’t working, unless of course your logic is funky. You will have the best PHP programming experience with error reporting set to report everything. If its on a live site, the errors can be emailed to you, and if its on your development server, then they can display on screen.

    Also, the php manual is awesome. It’s priceless when it comes to learning php.

  12. 12

    Can i ask what the great online community was?! Great post. Ive just moved on to learning PHP so this really does help! Thanks.

  13. 13

    Mike van Hoenselaar

    February 5, 2009 11:40 pm

    To #4, my own question ;-):

    Maybe my question was not correct, what I really want to know is the following:

    What is the best way to perform a search in multiple tables?

    Explanation: So if I have a inputbox on a website and the user types ‘Cheap prices of aProductname aTypename’. You have a lot of tables (pages, news, products, etc) to serach in. So how do you get the best results to search in those tables and the best relevant results.

    For now I use a php for loop that loops through all given tables that I want and performs a MATCH() query on that table on all words.
    All found records are put in an array with its relevance.
    After that I order on relevance and output to screen.

    Anyone know a better method?

  14. 14

    The answer to all these questions is: Use a framework, stupid! All PHP developers NOT using a framework are newbies.

  15. 15

    every PHP “developer” who directly starts working with frameworks and doesn’t care about how or why it works always will be a newbie.

    Actually, the best advice regarding php programming is to learn some other language.

  16. 16

    I believe one should really learn raw PHP before picking up a framework. Also, while all of these questions are easily solved using CakePHP or CodeIgniter, or another framework of your choice, if all you require is some form validation, straightforward PHP is the way to go. Frameworks surely let you reduce development times when it comes to bigger apps, but it’s no use wasting time setting up a framework when a really simple script could get you goin’ three times as fast, without increasing server load and page loading times.

  17. 17

    Thanks Jason, for all the answers and the very useful resources mentioned too!

  18. 18

    Good tips for beginners, except for #3. Globals shouldn’t be used so lightly and certainly not to get around scope problems (at least not without good understanding of scope).
    Better solutions are:
    1. Move that require_once outside of the function.
    2. Let the function return the config vars (you won’t be able to get them twice since it’s an require_once()).
    3. Use a class for it that reads the config file and remembers the vars. You can then call that class for the config vars.

    Seriously, don’t use globals for stuff like that.

  19. 19

    Typo: heading “3. required_once()-problem” should be “3. require_once()-problem”.

  20. 20

    RE: Mike van Hoenselaar the answer given should still be of help to you. Alternatively you might want to try a SQL statement similar to:

    SELECT pn.product_name, pn.product_id,, ns.news_id,, pg.page_id
    FROM tbl_product_name as pn, tbl_news as ns, tbl_pages as pg
    WHERE = $search_term
    OR pn.product_name = $search_term
    OR = $search_term

    Where $search_term is the input term they are searching for.

    Also, on a totally separate note, why on earth does every php article that appears on SM bring out such puerile, childish commentators?
    Mikemike, if you want to insult a group of developers it tends to be a smart move to make sure you understand words and meanings before you use them (see: s/inherit/inherent in your post).

  21. 21

    “from now on […] me will take care of…”

    you may not have the grammar skills, but you definitely have the coding chops!

  22. 22

    Using a framework teaches one very very little about a language, and I’d be willing to bet that if anyone is truly new to PHP, setting up CakePHP (or any other framework) would cause them to rip more hair out than trying to just sanitize form input.

  23. 23

    @Danny Matthews: The great online community was the w3schools forum Link. I linked to them in the article, as well. They’re a great collection of knowledgeable folks.

    To everyone else, thanks so much for the feedback! And don’t forget to send me your questions!

  24. 24

    I totaly disagree to declare global variables within a PHP application to get “everywhere”-access to them. If there is need for such kind of ancient coding styles, I suggest to read about the registry pattern (respective singleton pattern).

  25. 25

    Why are most articles on server side scripting always so basic on SM?? When i started development of web apps i always wanted to know how everything fits together. How to build and application like Facebook – what are the process it entails – from planning to development etc, technologies involved, what skills are required of you, problem solving tips etc.

  26. 26

    @ #4,

    better way to search in different tables, and present results in ONE query is MySQL function: UNION.

    Here is some info and examples about it (mysql dev page):

  27. 27


    I would like to say that there is a way to access a variable when loading external file through require_once in a function. It is not very known trick but you can return a value in a script – or better said a script can have a return value like a function can have. This means you can put a return statement at the end of a script. Then in a function you can do something like this:

    return require_once('path/to/file');

    which will result in that the function will return the variable from the return statement in loaded script. I myself use this when loading forms. I have my own written handler for form generating and validatig and common stuff. I create forms in external files, which I load throug a static method form::get_form(‘name_of_form’); this function then use the require_once to load that file. The loaded file look like this:

    $form = new form(.. init values ..);
    $form->addinput( .. init values ..);
    .. another form creating functions calls ..

    return $form;

    I hope this helps. And if you need to return multiple variables then array comes handy.

  28. 28

    re: #1
    PHP has an included library of filtering functions that was brought over from the PECL libraray. The work very well on filtering incoming data (or any data really)

    and more specifically for filtering GET and POST data and datatype filters:

  29. 29

    Hi Jason,
    I have been designing web pages for a few years now. In my designs I use css, html, jQuery. I am currently converting, which I designed, to WordPress so that it can be used as a CMS. PHP and jQuery are languages that I would like to learn but I don’t know where to start. I can use scripts and make them work, I can read PHP and see the patterns and make pages work but I don’t know where to start learning PHP from scratch.

    Usually I learn when I have a project and have to find out the information.

    Any suggestions?


  30. 30

    For fellow Mac users out there who work with XML, you’ve probably noticed that there is a serious lack of a good, lightweight XML inspector for OS/X. Siavash Etemadieh has just built a free web-based XML inspector at


↑ Back to top