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.

PHP-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

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

PHP, SQL,

↑ Back to top

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

    Nice. Handy lil tips there

    0
  2. 2

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

    0
  3. 3

    required_once( )- problem
    Good tips

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

    0
  5. 5

    @Josh:
    Thanks for adding that. Great point!

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

    0
  7. 7

    Spooky….

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

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

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

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

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

    0
  13. 13

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

    0
  14. 14

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

    0
  15. 15

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

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

    0
  17. 17

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

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

    0
  19. 19

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

    0
  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.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).

    0
  21. 21

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

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

    0
  22. 22

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

    0
  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!

    0
  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).

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

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

    0
  27. 27

    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.

    0
  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)

    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

    0
  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 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

    0
  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 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

    0
  31. 31

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

    0
  32. 32

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

    0
  33. 33

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

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

    0
  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

    0
  36. 36

    Hello,

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

    0
  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: Josbrafe@gmail.com
    Thanks

    0

↑ Back to top