Menu Search
Jump to the content X X
Smashing Conf Barcelona 2016

We use ad-blockers as well, you know. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

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

@titel2 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 class3, but I think it’s really better to take the time to write your own. There are tons of easy tutorials4 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 (mysqli5 and PDO6, 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

@igmuska7 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 page8 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 Link

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

@MikevHoenselaar10 asks:

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

To search multiple tables, start by using JOIN11 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 LIKE12-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-search13, 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

@korteev14 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, SimpleXML15 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.com16 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 namespaces17, which is very useful when parsing Flickr’s RSS feed, for example.

Further Resources Link

(al)

Footnotes Link

  1. 1 https://www.smashingmagazine.com/2009/02/05/ask-sm-pixel-width-decisions-rollover-buttons-modal-boxes/
  2. 2 http://twitter.com/titel
  3. 3 http://www.phpformclass.com/
  4. 4 http://www.google.com/search?q=PHP+form+validation
  5. 5 http://us.php.net/mysqli
  6. 6 http://us2.php.net/pdo
  7. 7 http://twitter.com/igmuska
  8. 8 http://www.xml.com/pub/a/2005/08/10/google-maps.html
  9. 9 http://twitter.com/DanBowles
  10. 10 http://twitter.com/MikevHoenselaar
  11. 11 http://dev.mysql.com/doc/refman/5.0/en/join.html
  12. 12 http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator_like
  13. 13 http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
  14. 14 http://twitter.com/korteev
  15. 15 http://us2.php.net/simplexml
  16. 16 http://www.w3schools.com/php/php_ref_simplexml.asp
  17. 17 http://www.w3.org/TR/REC-xml-names/
  18. 18 http://www.php.net/manual/en/
  19. 19 http://dev.mysql.com/doc/refman/5.0/en/
  20. 20 http://w3schools.invisionzone.com/
SmashingConf Barcelona 2016

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? Like SmashingConf Barcelona, on October 25–26, with smart design patterns and front-end techniques.

↑ Back to top Tweet itShare on Facebook

Advertisement

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

    Fearghal Murphy

    February 6, 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.

    0
  2. 2

    Nice. Handy lil tips there

    0
  3. 3

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

    0
  4. 4

    Samir Tuladhar

    February 5, 2009 5:23 pm

    required_once( )- problem
    Good tips

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

    0
  6. 6

    Jason Lengstorf

    February 5, 2009 6:18 pm

    @Josh:
    Thanks for adding that. Great point!

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

    0
  8. 8

    Spooky….

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

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

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

    0
  12. 12

    Danny Matthews

    February 5, 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.

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

    0
  14. 14

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

    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

    Paul Decowski

    February 6, 2009 3:20 am

    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

↑ Back to top