Differences
This shows you the differences between two versions of the page.
docs:programming:php:10_tips_that_every_php_newbie_should_know [2007/01/25 11:48] – created billh | docs:programming:php:10_tips_that_every_php_newbie_should_know [2008/08/03 00:25] (current) – external edit 127.0.0.1 | ||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ====== 10 Tips That Every PHP Newbie Should Know ====== | ||
+ | author: Jeffery Vaska | ||
+ | |||
+ | ===== Part 1 ===== | ||
+ | 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: | ||
+ | |||
+ | <code php> | ||
+ | class DB { | ||
+ | function DB() { | ||
+ | $this-> | ||
+ | $this-> | ||
+ | $this-> | ||
+ | $this-> | ||
+ | |||
+ | $this-> | ||
+ | mysql_select_db($this-> | ||
+ | } | ||
+ | } | ||
+ | |||
+ | // calls it to action | ||
+ | $db = new $DB; | ||
+ | </ | ||
+ | |||
+ | Simply edit the variables and include this in your files. This doesn' | ||
+ | |||
+ | <code php> | ||
+ | $result = mysql_query(" | ||
+ | </ | ||
+ | |||
+ | * More information can be found in the manual--be sure you read the comments: http:// | ||
+ | |||
+ | ==== Tip 2: Dealing with Magic Quotes ==== | ||
+ | PHP " | ||
+ | |||
+ | <code php> | ||
+ | function magicQuotes($post) { | ||
+ | |||
+ | if (get_magic_quotes_gpc()) { | ||
+ | if (is_array($post) { | ||
+ | return array_map(' | ||
+ | } 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 ' | ||
+ | * More information about magic quotes: http:// | ||
+ | * More information about SQL injection: http:// | ||
+ | * More information about regular expressions: | ||
+ | |||
+ | ==== 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' | ||
+ | |||
+ | <code php> | ||
+ | function escapeString($post) { | ||
+ | |||
+ | if (phpversion() >= ' | ||
+ | return array_map(' | ||
+ | } else { | ||
+ | return array_map(' | ||
+ | } | ||
+ | |||
+ | } | ||
+ | </ | ||
+ | |||
+ | * More information about mysql_real_escape_string: | ||
+ | * More information about SQL injection: http:// | ||
+ | |||
+ | ==== 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: | ||
+ | |||
+ | <code php> | ||
+ | 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 " | ||
+ | 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. | ||
+ | |||
+ | <code php> | ||
+ | print_r($result); | ||
+ | </ | ||
+ | |||
+ | The exit command stops your script from executing any further so you can specifically review your query results. | ||
+ | * More information about error_reporting: | ||
+ | * More information about print_r; http:// | ||
+ | |||
+ | ==== 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' | ||
+ | |||
+ | <code php> | ||
+ | if ($rs[' | ||
+ | $prfx = 'Mrs. '; | ||
+ | } elseif ($rs[' | ||
+ | $prfx = 'Ms. '; | ||
+ | } else { | ||
+ | $prfx = 'Mr. '; | ||
+ | } | ||
+ | |||
+ | echo $prfx.$rs[' | ||
+ | </ | ||
+ | |||
+ | You could rewrite it like this in a function: | ||
+ | |||
+ | <code php> | ||
+ | function makePrefix($prefix='' | ||
+ | { | ||
+ | if (!$prefix) return ''; | ||
+ | if ($prefix == 1) return 'Mrs. '; | ||
+ | if ($prefix == 2) return 'Ms. '; | ||
+ | if ($prefix == 3) return 'Mr. '; | ||
+ | } | ||
+ | |||
+ | echo makePrefix($rs[' | ||
+ | </ | ||
+ | |||
+ | 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:// | ||
+ | * More information about writing classes: http:// | ||
+ | Everything I've learned, more or less, came from the manual, trial and error and great help from the many fine people here at [[http:// | ||
+ | |||
+ | ===== Part 2 ===== | ||
+ | I wish I had known these 10 simple things the day I started working with PHP. This article is part II in the this series and is intended for newbies. The previous article is located here. | ||
+ | |||
+ | ==== Tip 6: Single and double quotes ==== | ||
+ | Single and double quotes confused me for some time and it really should not have. I see this quite often in the forum as well. It's very easy to understand that double quotes allow php to parse and single quotes do not. Here are some examples: | ||
+ | |||
+ | <code php> | ||
+ | $var = $value; // ok | ||
+ | $var = " | ||
+ | $var = ' | ||
+ | </ | ||
+ | |||
+ | (' | ||
+ | Oftentimes programmers will leave spaces around the ' . ' to make | ||
+ | things easier to read.) | ||
+ | |||
+ | <code php> | ||
+ | $var = 'This is the ' . $value . ' of things.'; | ||
+ | $var = "This is the $value of things."; | ||
+ | $var = 'This is the $value of things.'; | ||
+ | $var = This is the $value of things.; // error | ||
+ | |||
+ | $var = $array[' | ||
+ | $var = $array[" | ||
+ | $var = " | ||
+ | |||
+ | $var = 'Name: ' . $array[' | ||
+ | $var = "Name: $array[name]"; | ||
+ | $var = "Name: $array[" | ||
+ | $var = "Name: $array[' | ||
+ | |||
+ | exampleFunction($value); | ||
+ | exampleFunction(" | ||
+ | exampleFunction(' | ||
+ | </ | ||
+ | |||
+ | ==== Tip 7: Problems of style ==== | ||
+ | It's a matter of style and convenience to produce your scripts in such a way that make them easy to read and debug. If you are using a programming editor that highlights your code it will be easy to identify the various parts. This may explain why you find syntax that looks rather confusing at first. Some examples: | ||
+ | |||
+ | <code php> | ||
+ | $line = $result[' | ||
+ | $line = $result[" | ||
+ | $line = " | ||
+ | |||
+ | $line = $result[' | ||
+ | </ | ||
+ | |||
+ | If you are working with any kind of a team and/or plan on allowing others access to your work in the future it's etiquette to try to make it accessible and easy on the eyes. | ||
+ | |||
+ | ==== Tip 8: Ternary Operator ==== | ||
+ | The ternary operator is similar to an if/else statement except that it's more streamlined. This is a traditional if/else statement: | ||
+ | |||
+ | <code php> | ||
+ | if (empty($_POST[' | ||
+ | $action = ' | ||
+ | } else { | ||
+ | $action = $_POST[' | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | This example of a ternary operator will produce the same result as the previous example using less space. It makes use of ? and : just like if and else. | ||
+ | |||
+ | <code php> | ||
+ | $action = (empty($_POST[' | ||
+ | </ | ||
+ | |||
+ | Working with ternary operators do take a little more practice - be sure you test your work as you work through them. | ||
+ | * More information: | ||
+ | |||
+ | ==== Tip 9: Safe Queries ==== | ||
+ | Safe queries are really a subject for a lengthier tutorial, but I'm going to try to make a simple presentation here. I'm using functions in this example as opposed to the more traditional class technique. | ||
+ | A safe query will not return an error message that may reveal path information or give hackers accidental insider information. Certainly, security by obscurity is not an effective measure, but reducing error messages at the user end is desired once your site is launched. | ||
+ | We use the connection class from the previous article and a few functions to make this happen. Our first function performs the actual query using msyql_query. If the query string is empty it will return false. | ||
+ | |||
+ | <code php> | ||
+ | function safeQuery($query='' | ||
+ | { | ||
+ | global $db; | ||
+ | if (!$query) return false; | ||
+ | return mysql_query($query, | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | The next two sample functions are our means for performing queries. Note that our fetchArray() function will return an array of results while the fetchRow() function will simply return a row. If either function returns no results FALSE will be returned. | ||
+ | |||
+ | <code php> | ||
+ | // returns an array of records | ||
+ | function fetchArray($query='' | ||
+ | { | ||
+ | if ($result = safeQuery($query)) { | ||
+ | if (mysql_num_rows($result) > 0) { | ||
+ | while ($arr = mysql_fetch_assoc($result)) $rows[] = $arr; | ||
+ | return $rows; | ||
+ | } | ||
+ | } | ||
+ | return false; | ||
+ | } | ||
+ | |||
+ | // returns a single record | ||
+ | function fetchRecord($query='' | ||
+ | { | ||
+ | if ($row = safeQuery($query)) { | ||
+ | if (mysql_num_rows($row) > 0) { | ||
+ | return mysql_fetch_assoc($row); | ||
+ | } | ||
+ | } | ||
+ | return false; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | Now, with one simple line of code we can perform our query to return our predicted results. | ||
+ | |||
+ | <code php> | ||
+ | $results = fetchArray(" | ||
+ | |||
+ | // sample output results | ||
+ | if (!$results) { | ||
+ | echo 'No results.'; | ||
+ | } else { | ||
+ | // loop the data | ||
+ | foreach ($results as $result) { | ||
+ | echo $result[' | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | With this approach you can also define your queries more specifically for INSERT, DELETE, etc. and/or for repetitive tasks. Once you have a group of functions you are comfortable with you can recycle them in other projects. | ||
+ | If you understand how these safe query functions work then you are probably ready to explore the commonly used PEAR DB database abstraction class. This class, which is open source, will give you more flexibility, | ||
+ | A more complete tutorial regarding safe queries can be found at this site. Be sure to read the section regarding debugging your safe queries as well. | ||
+ | |||
+ | ==== Tip 10: A Strategy for Success ==== | ||
+ | And finally, I highly recommend using a pen, paper and plain english (or your language of preference) to work out your concepts first. Chances are that if you can explain what you need to do in plain language, you will both be able to explain the problem to others and ultimately solve your problem. You will be surprised how much easier it will be to program with a plan rather than making it up as you go along. | ||
+ | Conclusion | ||
+ | For the most part, this collection of 10 things I wish I knew when I started using PHP are quite simple, but they should be considered building blocks. Additionally, | ||
+ | Good luck programming! | ||
+ | |||
+ | ===== External Links ===== | ||
+ | * http:// | ||
+ | * http:// | ||
+ | |||
+ | |||