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 JavaScript1-related questions, from now on me, Jason Lengstorf2, will take care of your PHP- and MySQL-related questions.


You can just tweet me @jasonatennui3 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

@titel4 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 class5, but I think it’s really better to take the time to write your own. There are tons of easy tutorials6 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 (mysqli7 and PDO8, 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

@igmuska9 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 page10 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

@DanBowles11 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?

@MikevHoenselaar12 asks:

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

To search multiple tables, start by using JOIN13 in your MySQL query. A great introductory article on the concept is available here14. 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 LIKE15-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-search16, 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

@korteev17 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, SimpleXML18 is a great tool that makes parsing XML feeds really easy. There’s a great article here19 on how to use it, as well as a resource on w3schools.com20 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 namespaces21, which is very useful when parsing Flickr’s RSS feed22, for example.

Further Resources



  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25

↑ Back to topShare on Twitter

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.


Note: Our rating-system has caused errors, so it's disabled at the moment. It will be back the moment the problem has been resolved. We're very sorry. Happy Holidays!

  1. 1

    Nice. Handy lil tips there

  2. 2

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

  3. 3

    required_once( )- problem
    Good tips

  4. 4

    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.

  5. 5

    Thanks for adding that. Great point!

  6. 6

    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.

  7. 7
  8. 8

    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.

  9. 9

    @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.

  10. 10

    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.

  11. 11

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

  12. 12

    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?

  13. 13

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

  14. 14

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

  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

  31. 31

    If you’re getting into WordPress specifically, there’s a great series out there on In the Woods Link.

    As far as straight PHP development, I’d recommend coming up with a project you’d like to know how to build, then working toward that goal. I started with a very basic application to allow me to write text to a database and read it back out for multiple pages, then added on to it as I learned more about the language. Feel free to ask questions on Twitter @jasonatennui as you go along.

  32. 32

    We release very very fast pdoxml extension for PHP, released as open source. See at:

  33. 33

    PHP does have validation, it’s called E_ALL ;).

  34. 34

    Nice handy tips? I can see that there are a lot of newbies who have posted comments, so lets take an example shall we?

    I quote, “…but possible problems could be that you’re trying to access variables inside a function without declaring them as globals,…”

    What you certainly do not want in any PHP application is using global variables, what you want to be doing instead is to use encapsulation to prevent leakage that you would otherwise get from using globals.

    Bad advice given people, listen to real PHP developers who have years of experience, rather than some fashion magazine like this one – goto and subscribe to the rss feeds there, and pay attention to those who blog PHP – you’ll find the links on the right more useful and helpful to you than anything on this site.

  35. 35

    i want to display table in front end in they two columns only visible if i select on radio button and click submit button it goes to another page and show about that row full columns only it takes from db

  36. 36


    Codeigniter Form validation library has some weaknesses, see here. and also see how you can solve this problem here.

  37. 37

    Hello Jason Lengstorf,
    I have i problem with my .htaccess code. I create a new file from my simple_blog directory.
    This are the url Rewriting code I place in the .htaccess file.

    RewriteEngine on
    RewriteBase /simple_blog/
    RewriteRule .(gif|jpg|png|css|js|inc.php)$ – [L]
    RewriteRule pattern replacement [flags]
    RewriteRule ^admin/(w+) admin.php?page=$1 [Nc,L]
    RewriteRule ^admin/? admin.php [NC,L]
    RewriteRule ^(w+)/?$ index.php?page=$1
    RewriteRule ^(w+)/([w-]+) index.php?page=$1&url=$2

    This is the error am getting.

    Internal Server Error
    The server encountered an internal error or misconfiguration and was unable to complete your request.

    Please contact the server administrator, admin@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.

    More information about this error may be available in the server error log.

    Pls help my to check the code. and mail me the solution.
    My email address:

↑ Back to top