Smashing Magazine - we smash you with the information that will make your life easier. really.

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

Advertisement

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.

Get-vars in Ask SM [PHP]: Form Validation, Converting MySQL to XML

Please feel free to submit your PHP/MySQL-related questions in our forum (you will need to sign up; yes, the forum is not officially launched yet, but it is running!). Or, 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

@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

@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
<{$entry['datatype']}>
  <point lng="{$entry['longitude']}" lat="{$entry['latitude']}" />
  <icon image="{$entry['icon']}" class="local" />
</{$entry['datatype']}>
XML_OUTPUT;
}

3. require_once()-problem

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

@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

@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 w3schools.com 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"?>
  <people>
    <person>
      <name>John Doe</name>
      <age>27</age>
    </person>
    <person>
      <name>Jane Doe</name>
      <age>31</age>
    </person>
  </people>

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

<?php
  $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

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

(al)

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.

    Post Rating
    1 Star2 Stars3 Stars4 Stars5 Stars (No votes yet)
    Loading ... Loading ...

    Tags: ,

    Advertising
    1. 1
      Bdog
      February 5th, 2009 5:02 pm

      Nice. Handy lil tips there

    2. 2
      Reed
      February 5th, 2009 5:23 pm

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

    3. 3
      Samir Tuladhar
      February 5th, 2009 5:23 pm

      required_once( )- problem
      Good tips

    4. 4
      Josh
      February 5th, 2009 6:12 pm

      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
      Jason Lengstorf
      February 5th, 2009 6:18 pm

      @Josh:
      Thanks for adding that. Great point!

    6. 6
      DKumar M.
      February 5th, 2009 7:42 pm

      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
      bert
      February 5th, 2009 8:11 pm

      Spooky….

    8. 8
      mikemike
      February 5th, 2009 8:15 pm

      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
      Josh
      February 5th, 2009 10:01 pm

      @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
      Brian Gottier
      February 5th, 2009 11:14 pm

      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
      Danny Matthews
      February 5th, 2009 11:39 pm

      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 5th, 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
      Karl
      February 5th, 2009 11:45 pm

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

    14. 14
      Fearghal Murphy
      February 6th, 2009 12:16 am

      The form validation example given leads to Clonefish, which is an eyesore to be blunt. Try http://www.livevalidation.com/ – much better.

    15. 15
      Harry S.
      February 6th, 2009 1:35 am

      @karl
      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
      Hoss
      February 6th, 2009 2:00 am

      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
      OnWebDev
      February 6th, 2009 2:10 am

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

    18. 18
      Roy
      February 6th, 2009 2:55 am

      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
      Paul Decowski
      February 6th, 2009 3:20 am

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

    20. 20
      Steerpike
      February 6th, 2009 4:38 am

      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.name, ns.news_id,
      pg.name, pg.page_id
      FROM tbl_product_name as pn, tbl_news as ns, tbl_pages as pg
      WHERE pg.name = $search_term
      OR pn.product_name = $search_term
      OR ns.name = $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
      Bryan
      February 6th, 2009 7:06 am

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

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

    22. 22
      Nami
      February 6th, 2009 10:00 am

      @Karl
      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
      Jason Lengstorf
      February 6th, 2009 10:02 am

      @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
      unset
      February 6th, 2009 12:55 pm

      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
      Dele
      February 6th, 2009 7:07 pm

      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
      LukasS
      February 7th, 2009 5:21 pm

      @ #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): http://dev.mysql.com/doc/refman/5.0/en/union.html

    27. 27
      westrem
      February 8th, 2009 1:03 pm

      Hello,

      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
      Ryan
      February 9th, 2009 7:04 am

      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)

      http://www.php.net/filter

      and more specifically for filtering GET and POST data and datatype filters:
      http://www.php.net/manual/en/function.filter-input.php
      http://us2.php.net/manual/en/filter.constants.php

    29. 29
      Rizwan
      February 11th, 2009 10:48 am

      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 http://www.hcdmediagroup.com, 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?

      Thanks.
      Rizwan

    30. 30
      Tyler Tate
      February 12th, 2009 6:36 am

      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 http://twitter.com/ssetem has just built a free web-based XML inspector at http://www.vyre.com/other_files/com.vyre.viewer.VyreXmlInspector/index.html

    31. 31
      Jason Lengstorf
      February 14th, 2009 6:56 pm

      @Rizwan:
      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
      Anton Pitak
      February 24th, 2009 3:09 pm

      We release very very fast pdoxml extension for PHP, released as open source. See at: http://sourceforge.net/projects/pdoxml/

    33. 33
      Robin Card
      March 7th, 2009 3:16 am

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

    34. 34
      Les
      March 7th, 2009 3:20 pm

      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 http://www.planet-php.org 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.

    1. 00

      There are no trackbacks at this time. If you are interested in leaving a trackback, please use this URL.

    Leave a Comment

    Make sure you enter the * required information where indicated. Please also rate the article as it will help us decide future content and posts. Comments are moderated – and rel="nofollow" is in use. Please no link dropping, no keywords or domains as names; do not spam, and do not advertise!



    Advertisement Advertise with us!
    Join in Smashing Forum
    Post your job