#native_company# #native_desc#
#native_cta#

10 Tips That Every PHP Developer Should Know, Part 2

By Jeffery Vaska
on August 12, 2005

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:

$var = $value; // ok
$var = "$value"; // ok, but double quotes are not necessary
$var = '$value'; // will not work (single quotes will not allow parsing)

('.' the period adds/connects variables, functions, etc. together. 
Oftentimes programmers will leave spaces around the ' . ' to make 
things easier to read.)

$var = 'This is the ' . $value . ' of things.'; // ok - preferred 
technique
$var = "This is the $value of things."; // ok, but harder to read/debug
$var = 'This is the $value of things.'; // will not parse $value
$var = This is the $value of things.; // error

$var = $array['name']; // ok, generally the preferred technique
$var = $array["name"]; // ok, but why use double quotes if they are not 
necessary?
$var = "$array[name]"; // ok, but harder to read/debug - poor coding 
style

$var = 'Name: ' . $array['name']; // ok - preferred technique
$var = "Name: $array[name]"; // ok, but harder to read/debug - poor 
coding style
$var = "Name: $array["name"]"; // error
$var = "Name: $array['name']"; // error

exampleFunction($value); // ok
exampleFunction("$value"); // ok, but double quotes are not necessary
exampleFunction('$value'); // will not parse $value

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:
$line = $result['name'] . ' ' . $result['last_name']; // ok - easy to 
read/debug
$line = $result["name"] . ' ' . $result["last_name"]; // ok, but why 
use double quotes if they are not necessary?
$line = "$result[name] $result[last_name]"; // ok - but much harder to 
read/debug - poor coding style

$line = $result['name'] . ' ' . doSomething($result['last_name']); // 
ok - preferred method (using a function)
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:
if (empty($_POST['action'])) {
	$action = 'default';
} else {
	$action = $_POST['action'];
}
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.
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
Working with ternary operators do take a little more practice – be sure
you test your work as you work through them.

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.
function safeQuery($query='')
{
	global $db;
	if (!$query) return false;	
	return mysql_query($query, $db->link);
}
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.
// 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.
$results = fetchArray("SELECT id,field1 FROM records");

// sample output results
if (!$results) {
	echo 'No results.';
} else {
	// loop the data
	foreach ($results as $result) {
		echo $result['id'] . ' ' . $result['field1'];
	}
}
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, debugging features and it will work on more than just a
MySQL database.
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, some of the concepts presented are good
examples of how you can build your own custom functions thus improving
your speed and skill.
Good luck programming!