10 Tips That Every PHP Newbie Should Know
I wish I had known these 10 tips the day I started working with PHP. Instead of learning them through painstaking process, I could have been on my way to becoming a PHP programmer even sooner! This article is presented in two parts and is intended for folks who are new to PHP.
Tip 1: MySQL Connection Class
The majority of web applications I’ve worked with over the past year have used some variation of this connection class:
class DB {
function DB() {
$this->host = "localhost"; // your host
$this->db = "myDatabase"; // your database
$this->user = "root"; // your username
$this->pass = "mysql"; // your password
$this->link = mysql_connect($this->host, $this->user,
$this->pass);
mysql_select_db($this->db);
}
}
// calls it to action
$db = new $DB;
Simply edit the variables and include this in your files. This doesn’t require any knowledge or special understanding to use. Once you’ve added it to your repertoire, you won’t likely need to create a new connection class any time soon. Now you can get to work and quickly connect to your database without a lot of extra markup:
$result = mysql_query("SELECT * FROM table ORDER BY id ASC LIMIT 0,10");
More information can be found in the manual–be sure you read the comments: http://www.php.net/mysql_connect/
Tip 2: Dealing with Magic Quotes
PHP “automagically” can apply slashes to your $_POST data for security purposes. It’s an important measure to prevent SQL injections. However, slashes in your scripts can wreak havoc. This is an easy method for dealing with them. The way to handle the slashes is to strip them from our variables. However, what if the magic quotes directive is not enabled?
function magicQuotes($post) {
if (get_magic_quotes_gpc()) {
if (is_array($post) {
return array_map('stripslashes',$post);
} else {
return stripslashes($post);
}
} else {
return; // magic quotes are not ON so we do nothing
}
}
The script above checks to see if magic quotes is enabled. If they are, it will determine if your $_POST data is an array (which it likely is) and then it will strip the slashes accordingly.
Understand that this is not true ‘validation’. Be sure to validate all your user-submitted data with regular expressions (which is the most common way to do so).
More information about magic quotes: http://www.php.net/ magic_quotes/
More information about SQL injection: http://www.php.net/manual/en/security.database.sql-injection.php/
More information about regular expressions: http://www.php.net/pcre/
Tip 3: Safely Query Database with mysql_real_escape_string
When you are ready to query your database you will need to escape special characters (quotes for instance) for safety’s sake by adding slashes. We apply these before we insert variables into our database. Once again, we need to determine which version of PHP you are running first:
function escapeString($post) {
if (phpversion() >= '4.3.0') {
return array_map('mysql_real_escape_string',$post);
} else {
return array_map('mysql_escape_string',$post);
}
}
More information about mysql_real_escape_string: http://www.php.net/ mysql_real_escape_string/
More information about SQL injection: http://php.belnet.be/manual/en/security.database.sql- injection.php
Tip 4: Debugging
If you search the forum there are many good threads with rules about debugging. The single most important thing you can do is ask PHP to report errors and notices to you by adding this line at the beginning of your scripts:
error_reporting(E_ALL);
This will keep you in line as you learn by printing out errors to your screen. The most common error that E_ALL reports is not actually an error, but a notice for an “Undefined index”. Typically, it means that you have not properly set your variable. It’s easy to fix and keeps you programming correctly.
Another convenient tool while working with queries is print_r(). If your query is returning null or strange results, simply place this after your query command and it will display all the contents of the $result array.
print_r($result); exit;
The exit command stops your script from executing any further so you can specifically review your query results.
More information about error_reporting: http://www.php.net/ error_reporting/
More information about print_r; http://www.php.net/print_r/
Tip 5: Writing Functions (and Classes)
Initially I thought that tackling functions and classes would be difficult–thankfully I was wrong. Writing a function is something I urge all newbies to start doing immediately–it’s really that simple. You are instantly involved in understanding how to produce more efficient code in smaller pieces. Where you might have a line of code that reads like this:
if ($rs['prefix'] == 1) {
$prfx = 'Mrs. ';
} elseif ($rs['prefix'] == 2) {
$prfx = 'Ms. ';
} else {
$prfx = 'Mr. ';
}
echo $prfx.$rs['name'].' '.$rs['last_name'];
You could rewrite it like this in a function:
function makePrefix($prefix='')
{
if (!$prefix) return '';
if ($prefix == 1) return 'Mrs. ';
if ($prefix == 2) return 'Ms. ';
if ($prefix == 3) return 'Mr. ';
}
echo makePrefix($rs['prefix']) . $rs['name'] . ' ' . $rs['last_name'];
Now that you’ve written this function, you can use it in many different projects!
An easy way to describe classes is to think of it as a collection of functions that work together. Writing a good class requires an understanding of PHP 5’s new OOP structure, but by writing functions you are well on your way to some of the greater powers of PHP.
More information about writing functions: http://www.php.net/manual/en/language.functions.php
More information about writing classes:
http://www.php.net/manual/en/language.oop5.php
Everything I’ve learned, more or less, came from the manual, trial and error and great help from the many fine people here at PHPBuilder. Good luck programming–and come back soon for Part 2 in this series!
55 reasons to design in XHTML/CSS
In no particular order 55 reasons for me to do “tableless” websites using valid XHTML for markup, CSS for layout and Flash sparingly, only as an ingredient. By tableless I mean avoiding tables (or a tagsoup of unnecessary divs substituting table trs and tds) for layout purposes and aiming towards as semantic markup as possible. Some of the reasons are “over HTML”, some “over Flash full monty” and some over both.
I know this topic has been discussed a plenty, I just needed to reaffirm myself
Here we go:
- You can get free links from showcase sites like zengarden, stylegala, cssimport or cssbeauty
- You don’t have to spend extra thought and time deciding on styling the mark up of your document (upper- or lowercase, quotes or no quotes on attributes)
- You don’t need to spend extra thought on which tags should be closed and which can (or should) be left open
- You “help” the search engines to deliver more relevant content using semantic markup
- You can save in bandwidth costs and visitors will see them faster by making slimmer pages
- It’s going to be easier for you to switch to XHTML 2.0 which will give you more semantic tools
- Once you’ve practised enough, coding pages becomes a whole lot simpler and faster than any table/tr/td tagsoup
- When the coding is faster you can spend more time on thinking about the user experience
- Thinking about semantics of a document helps you to make design and information architecture decisions
- You can quickly make a dummy site to test your sites information architecture and append a look and feel later with only minor code changes
- You can do the design after most of the backend is done which will help your client (or boss) to think realistically about how much work is still needed
- It’s possible to link directly to your content pages (compared to Flash)
- browser controls like text-size and back and forward buttons work (compared to Flash)
- Redesigns and realigns over the whole site are simpler
- it’s simpler to make small last minute changes to your designs
- Clean markup makes it easier or even unnecessary to build a CMS
- Clean markup makes it easier for another developer to jump on board
- You can make the backend almost totally independently from the frontend design, by completely different person
- You have plenty of ways to play with the markup trying to optimize for search engines, without affecting visible layout
- You have total control on print layouts of your pages
- Your sites are automatically accessible to all kinds of browsers
- Promoting web standards will help your work in the future, not having to code differently to each browser
- With all elemets closed you mark up look cleaner
- Well-formed code ensures your site works in more browsers
- Well-formed code would help browser coders to spend more time on useful features than rendering engines that try to understand borken code
- Your website will work in future browsers
- Your website works in mobile (and other new) devices
- You learn the basics of XML which has many other uses
- CSS files are saved in browser cache for fast retrieval and less bandwidth use
- Your documents are easy to convert back and forth another format using XSLT
- Thinking semantics makes you think more about the content
- Learning semantics makes you appreciate organization and write your other documents (even emails) in more organized way
- You can write new technologies in your CV or portfolio
- Modern browsers render a valid document faster
- You feel better about yourself when you are making sites “the right way”
- They are doing it: Dan Cederholm, Jeffrey Zeldman, Jason Santa Maria, Shaun Inman, Cameron Moll, Douglas Bowman, Dave Shea…
- You will belong in a “movement”, make good contacts etc.
- You learn to appreciate newer browsers which makes for more competition and later for better browsers
- Blink tag is gone
- Strict coding makes you learn to see mistakes quicker
- You can aim to making some money writing a book about it
- There are more job opportunities if you know these new ways
- You learn better to understand how a browser works
- You can use hacks and techniques with cool names like “be nice to Opera”
- you start to care more about metadata, document and character types
- With more people making slimmer pages, the amount of data moving in the whole web will be smaller and all connections faster
- XHTML has a cooler name than HTML
- There are more people thinking about the advantages and disadvantages and coding tricks of XHTML which makes for a bigger learning forum
- You can use basically same markup template for many different websites
- Learning to read and write it fast makes it possible to use cheaper tools (notepad)
- Google knows this:
- 4,380,000 xhtml better than html > 4,370,000 html better than xhtml
- 206 “xhtml is better than html” > 87 “html is better than xhtml”
- 2,130,000 xhtml sucks < 10,300,000 html sucks
- When all browsers start to understand the correct MIME-type (xml), you don’t have to convert all your websites from html, just to switch to correct MIME
- By more people using xhtml you ensure that in the future IE will need to understand the correct MIME-type
- Accessibility is enforced with requiring Alt attribute for images
- There just aren’t this many reasons to use HTML or entirely Flash instead