Writing Solid PHP Code 2 - Naming and Style

January 26, 2009 by admin  
Filed under Articles, PHP

Having a consistent style makes your PHP code more readable and maintainable. Even in projects where you are the only programmer, once the project progresses to a certain size it can become difficult to maintain.

Variable Names

Variable names should be very descriptive. They should give anyone that is not familiar with your script to understand what its for without much digging.

Variable names should all follow the same conventions. It doesn't matter if you use camel casing (YourVariableName), lower camel case (yourFunctionName), or underscores (your_variable_name), as long as all the variable names have the same style.

It is a good idea to include the scope of the variable in the name. For example, if you have a function or set of functions dedicated to parsing a string you may want to start the variable name with "parse."

Function Names

Function names should also be very descriptive and follow a defined convention. Function names should be prefixed with the unit they are in. For example, if you have a file named databaseFunctions.php you might prefix all the functions within that file with dbFuncs_ or something similar.

Function names should describe the action taking place. For example, instead of "StringParser()" use "ParseString()."

Indentation

Indentation is very important as it makes reading the code easier. Proper indentation can help you keep track of loops, conditional statements, and blocks of code. Each level should be indented a step further. The following snippet is a good example of proper indentation:

<?php
    $loopVariable = 35;
    for ($loopCounter = 1; $loopCounter < 25; $loopCounter++)
    {
        $loopVariable = $loopVariable*$loopCounter;
        if (($loopVariable % 2) == 1)
        {
            echo "Even<br >n";
        }
    }
?>

Using good techniques such as proper naming and indentation may seem unneccesary for small projects. However, for larger projects it is essential for writing maintainable code.

del.icio.us Digg Facebook Google reddit SlashDot StumbleUpon Technorati

Writing Solid PHP Code 1 - Error Handling

January 20, 2009 by admin  
Filed under Articles, PHP

This is the first in a multiple part series on writing solid PHP code. By solid I mean fast, efficient, maintainable and secure code.

This first article deals with error handling. Error handling can stop problems in your application early in their tracks and take appropriate action. Error handling has the added benefit of adding professionalism and also making debugging easier.

Error handling should be applied to any action that has the possibility of failing. Failures in your application are often the result of some unexpected user input, user input should hence always be checked for vailidity.

The most simplistic way of employing error handling is using die(). die() takes a single string argument that it will output and then terminate the script.

Example:

<?php
mysql_connect("localhost", "root", "password") or die(mysql_error());
echo "Connected to MySQL the MySQL server! <br \>";
mysql_select_db("dbtable") or die(mysql_error());
echo "Connected to Database";
?>

The above example tries to connect to a database, and produces the MySQL error if it failed. It then tries to select a table within the database and also produces the MySQL error if it fails. These are both actions that could fail for many reasons: the connection to the the login information could be incorrect, the connection to the database could be lost, or the table might not exist. Even in this short example there are many reasons why it could potentially fail.

Since this example does only two things, it is okay to terminate the script upon failure. If we have a larger script, however, we may want to note the error and continue running. This is where die() falls short, not only can we not continue executing but the message is outputted to the page. If our script produces an error we want to log it for the administrator to view later as well as keep it hidden from our users.

<?php
mysql_connect("localhost", "root", "password") or trigger_error(mysql_error(), E_USER_ERROR);
echo "Connected to MySQL the MySQL server! <br \>";
mysql_select_db("dbtable") or trigger_error(mysql_error(), E_USER_ERROR);
echo "Connected to Database";
?>

This example uses the trigger_error() function to throw the error. An error will terminate the script while warnings and notices will allow the script to continue running. Below is a list of types of errors you can throw with trigger_error(). Also note an error can have multiple error types.

  • E_WARNING
  • E_NOTICE
  • E_USER_ERROR
  • E_USER_WARNING
  • E_USER_NOTICE

For a full list, visit the PHP documentation. Note that not all of the error types in the PHP documentation can be used with trigger_error().

For some errors, notices, and warnings will be outputted to the page. This is good for debugging but bad for live sites. To change this open your php.ini file in your php directory and search for the following line

display_errors = On

Change 'On' to 'Off' and save the configuration file and restart your web server. Make sure log_errors is set to 'On' so that all the errors are saved to a log file for you to review later.

Look for more articles on writing solid PHP code.

del.icio.us Digg Facebook Google reddit SlashDot StumbleUpon Technorati

How to Create an AJAX Based Voting System

January 11, 2009 by admin  
Filed under Javascript, PHP, Tutorials

This tutorial describes how to create a voting system with stars like below. We assume you have a web server that can run php scripts, a MySQL database, and a browser with javascript enabled.


Except we're gonna take it a step further and include the code to submit the vote (via AJAX) and return the new average rating.

We need 3 graphics for this tutorial: The a lit up star, a blank star, and a loading graphic. Shown below.

Next we need some CSS to style the stars for being lit up and blank:

<style type="text/css">
.starOn{
background-image: url("/images/full-star.gif");
background-repeat: no-repeat;
width: 10px;
height: 10px;
}
.starOff{
background-image: url("/images/clear-star.gif");
background-repeat: no-repeat;
width: 10px;
height: 10px;
}
</style>

Now lets write the PHP code to display the rating stars. This code can be inserted into a PHP script where you have multiple items to rate. The $item variable must be unique. Name this file displayStars.php.

function displayRating($item)
{
echo "<div id=\"processingDiv-$item\" style=\"display:none\">\n";
?> 
<img src="ajax-loader.gif"></div>
<?php
echo "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>\n";
for ($i=1; $i<=10; $i++)
{
if ($i == 1) $class = "starOn"; else $class = "starOff";
echo "<td>\n";
echo "<div class=\"$class\" id=\"ratings-$item-$i\" onmouseout=\"javascript:HoverStars('$item', 1)\" onmouseover=\"javascript:HoverStars('$item', $i)\" onmouseup=\"javascript:SubmitVote($i, '$item')\"></div>\n";
echo "</td>\n";
}
echo "</tr></table>\n";
 
}

Notice the javascript functions for onmouseout, onmouseover, and onmouseup. onmouseout and onmouseover will handle lighting up the stars while SubmitVote() will be our javascript AJAX function to submit it to our server side script.

Here's all the javascript for lighting up the stars as well as the AJAX, put this in displayStars.php. This will send the rating, and ajaxSubmit will show the loadingDiv while the request is being sent and targetDiv will display the data returned from our vote.php script. targetDiv should be the name of the Div you want it to display in, so for example you may name them targtDiv-0, targetDiv-1 for item 0, 1, and so on.

<script type="text/javascript">
function ajaxSubmit(url, processingDiv, targetDiv)
{
targetArea = document.getElementById(targetDiv);
processingArea = document.getElementById(processingDiv);
 
var xmlHttp;
try
{ xmlHttp=new XMLHttpRequest(); }
catch (e)
{
 try
  { xmlHttp=new ActiveXObject('Msxml2.XMLHTTP'); }
   catch (e)
    {
    try
     { xmlHttp=new ActiveXObject('Microsoft.XMLHTTP'); }
    catch (e)
     {
      alert('Your browser does not support AJAX!');
      return false;
     }
   }
 }
 
xmlHttp.onreadystatechange=function()
 {
  if(xmlHttp.readyState==4)
   {
    processingArea.style.display = 'none';
    targetArea.innerHTML = xmlHttp.responseText;
   }
}
 
processingArea.style.display = 'block';
xmlHttp.open('GET',url,true);
xmlHttp.send(null);
}
 
function SubmitVote(vote, item)
{
var poststr = 'vote.php' +
'?item=' +  item + 
'&vote=' +  vote;
 
LockStars(item, vote);
ajaxSubmit(poststr, 'processingDiv-'+item, 'ratingDiv-'+item);
}
 
function HoverStars(item, star)
{
var starCount;
for (starCount=1; starCount<=star; starCount++) 
 document.getElementById('ratings-'+item+'-'+starCount.toString()).className = 'starOn';
for (starCount=star+1; starCount<=10; starCount++) 
 document.getElementById('ratings-'+item+'-'+starCount.toString()).className = 'starOff';
}
 
function LockStars(item, star)
{
var starCount;
for (starCount=1; starCount<=star; starCount++) 
{
document.getElementById('ratings-'+item+'-'+starCount.toString()).className = 'starOn';
document.getElementById('ratings-'+item+'-'+starCount.toString()).onmouseover = null;
document.getElementById('ratings-'+item+'-'+starCount.toString()).onmouseout = null;
document.getElementById('ratings-'+item+'-'+starCount.toString()).onmouseup = 'javascript:void(0);';
}
for (starCount=star+1; starCount<=10; starCount++) 
{	
document.getElementById('ratings-'+item+'-'+starCount.toString()).className = 'starOff';
document.getElementById('ratings-'+item+'-'+starCount.toString()).onmouseover = null;
document.getElementById('ratings-'+item+'-'+starCount.toString()).onmouseout = null;
document.getElementById('ratings-'+item+'-'+starCount.toString()).onmouseup = 'javascript:void(0);';
}
}
</script>

ajaxSubmit(url, processingDiv, targetDiv) submits the URL 'url' and displays the processingDiv and returns this server side script's output to targetDiv which in this case is the updated average rating.

SubmitVote(vote, item) Takes an integer 'vote' and submits it for 'item'.

HoverStars(item, star)Lights up the stars for 'item' up to 'star'. The function is called on onmouseout with star 1 to return it to it's initial value.

LockStars(item, star) Locks the stars after the vote has been submitted

The following PHP code displays the stars for 10 items. Put this in displayStars.php.

for ($item=0; $item<=10; $item++)
 displayRating($item);
function displayRating($item)
{
echo "<div id=\"processingDiv-$item\" style=\"display:none\">\n";
?>
<img src="ajax-loader.gif"></div>
<?php
echo "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>\n";
for ($i=1; $i<=10; $i++)
{
if ($i == 1) $class = "starOn"; else $class = "starOff";
echo "<td>\n";
echo "<div class=\"$class\" id=\"ratings-$item-$i\" onmouseout=\"javascript:HoverStars('$item', 1)\" ";
echo "onmouseover=\"javascript:HoverStars('$item', $i)\" onmouseup=\"javascript:SubmitVote($i, '$item')\"></div>\n";
echo "</td>\n";
}
echo "</tr></table>\n";
}

Now create a database for all the items with all the fields you need (such as the item name, description, and whatever else you need) as well as an integer 'votes' and a decimal 'votesavg'.

The following PHP code should be in a separate PHP file for handling the server side processing of the vote. For this example I named it vote.php. Make sure that the 'item' displayed in the previous file corresponds to the item's id in the database.

$dbhost = "localhost";
$dbuser = "root";
$dbpass = "yourpassword";
$db = "yourdatabase";
 
$connection = mysql_connect($dbhost, $dbuser, $dbpass);
 
if (isset($_REQUEST["item"])) $item = $_REQUEST["item"];
if (isset($_REQUEST["vote"])) $vote = $_REQUEST["vote"];
if ((is_numeric($vote)) && ($vote <= 10))
  $item = mysql_escape_string($item);
  SubmitVote($item, $vote);
}
 
function SubmitVote($item, $vote)
{
$getVoteQuery = "SELECT voteavg, votes from yourtable where id = $item";
$getVoteResult = mysql_query($getVoteQuery);
 
$currentVoteCount	= mysql_result($getVoteResult, 0, "votes");
$currentVote		= mysql_result($getVoteResult, 0, "voteavg");
 
$newVoteCount = $currentVoteCount+1;
$newVote = (($currentVote * $currentVoteCount)+$vote) / ($newVoteCount);
 
$newVote = Round($newVote, 2);
$updateVoteQuery = "UPDATE `yourtable` SET `voteavg`=$newVote, `votes`=$newVoteCount WHERE id = $item;";
$updateVoteResult = mysql_query($updateVoteQuery);
 
echo "$newVote";
}
 
mysql_close($connection);

In PHP files that serve AJAX, make sure there is no extraneous output before or after the <?php ?> tags as they will be returned in the AJAX request (unless of course you want it to be returned)

So now we have just two files our main file, displayStars.php and vote.php. When you hover your mouse over the stars, they light up and once you vote, they are locked on that rating and will not let you vote again unless you refresh.

The server side script takes the rating and returns the new average rating to display in the ratingDiv.

So lets say you have a table with a list of videos with the title, description, location, and so on you would add two extra columns, `votes` and `voteavg`. This is to keep track of how many votes there are, and what the average vote is.

You can download a working example below, just unzip the files and follow the directions in readme.txt.

AJAX Voting Example

Conclusion and further reading

AJAX is a powerful technology and an integral part of web 2.0. Keep an eye out for more AJAX tutorials.

del.icio.us Digg Facebook Google reddit SlashDot StumbleUpon Technorati

Installing Wordpress 2.7

December 28, 2008 by admin  
Filed under Tutorials

Start off by downloading Wordpress from the official Wordpress download page. All the files come in a single zip file.

wordpress-download

Open the zip file and extract the files. In most zip programs you can just drag and drop the files into a folder. Once they are extracted, copy them to your website via FTP. If you are installing locally, copy the files into your document root folder.

wordpress-extract-files

Before we start installing Wordpress, we need to create a database for it.

If you have access to PhpMyAdmin then login and select Databases.

phpmyadmin-databases

Scroll down to the area named ‘Create new database’ and enter the name of your database. You can name it whatever you want but you need to remember what you named it for later. Click create.

phpmyadmin-create-database

If you don’t have access to PhpMyAdmin and your host provides a control panel, look for an area named ‘MySQL Manager’ or ‘Manage Databases’ or something along those lines. Go there to create the database. Remember which user has access to that database.

If you are installing on your local computer or have shell access, run the following commands to create your database.

>  mysql
mysql> create database wordpress;

Where ‘wordpress’ is the name of your database. You may need to change to your MySQL bin directory to get to the MySQL prompt.

Now that the database is created, navigate your browser to your website. If you copied  the files to a subdirectory, go there. You should see a page prompting to create a configuration file. Click the button to create the configuration file.

You will be prompted with a welcome screen that lists the information you will need. Click “Let’s Go.”

wordpress-install-welcome

You will be prompted with a page to enter the database information.

wordpress-database-setup

Database Name: The name of the database we created earlier
User Name: User with access to database (often ‘root’)
Password: Password for the user
Database Host: localhost if the MySQL server is on the same server. Note that many hosts have a separate host for the MySQL server. Check your control panel for this information)
Table prefix: The characters that will precede every table name. This is mainly useful for people who use hosts that restrict the number of databases they can have. Users may install several web applications in the same database and using the table prefixes helps prevent name conflicts.

If you get the page “Error establishing database connection,” go back and make sure all the information in the previous page is correct. Note that root may not have a password set, in which case create a password or leave the field blank.

wordpress-error-page

If all the database information is correct, you should see a page with the button “Run the Install.” Click the button to install!

wordpress-start-install

Next, you should see a page prompting you for the name of your blog and your email. You can always change these later but enter your information.

There is also a checkbox to allow your blog to be searched by search engines. Most people want keep this checked, otherwise your blog won’t be listed!

Click ‘Install Wordpress.’

wordpress-blog-information

Next you will be see a page with your username and password.

Copy the password into notepad and click “Log In.”

wordpress-done-login

Enter your username “admin” and your randomly generated password. and click “Log in.”

wordpress-login

Once logged in, click the User menu item on the left side.

wordpress-users

Click on ‘admin’ from the user list.

wordpress-users-admin

Enter a new password for the admin account.

wordpress-reset-password

Now that we have a password we can actually remember, let’s make our first post. Click ‘Add New’ under the ‘Posts’ heading on the left menu.

wordpress-add-post-menu

Enter your post title and body, and click the ‘Publish’ button on the right side.

Go back to the main site, if everything went to plan, you should see your blog with your new post!

wordpress-view-post

Conclusion and further reading.

Wordpress is one of the best blogging web applications available today. There are a huge amount of themes and plugins to turn your blog into what you want it to be.

Check out our other tutorials on installing (and creating your own!) plugins and themes.

Visit the Wordpress ‘Extend’ section to find new themes and plugins.

del.icio.us Digg Facebook Google reddit SlashDot StumbleUpon Technorati

Installing Apache, MySQL, and PHP on Windows with WAMP (The easy way)

December 25, 2008 by admin  
Filed under Apache, MySQL, PHP, Tutorials

This tutorial explains, step-by-step, how to install Apache, MySQL and PHP on Windows the easy way using WAMP. WAMP is an all-in-one program bundle that includes preconfigured versions of Apache, MySQL, and PHP.

Start off by downloading the latest version of WAMP from the WAMP download page.

wamp-download-page

A warning message appears warning you not to install with previous versions of WAMP. If you have an earlier version of WAMP installed, uninstall it.c Click yes.

wamp-warning-message

The WAMP setup welcome screen appears, click next.

wamp-setup-welcome

The license agreement dialog will appear, accept and click next.

wamp-install-destination-folder

Choose your installation directory (Note that Apache, MySQL, and PHP will all be installed under this directory). Click next.

A dialog prompting you to choose what icons to load will appear, choose which icons to load and click next.

wamp-setup-icons

Now we are ready to install, verify the information is correct and click install.

wamp-install-copying-files

After installation, a message box will prompt you to select your default browser for WAMP.

wamp-default-browser

Next, a message box will ask you to install the default WAMP homepage. This will create an index.php in your document root to show that everything is working correctly. If you select yes, you can easily overwrite this file later.

Next, a dialog prompting you for PHP mail configuration will appear. This is for scripts that can automatically send email. If you do not yet have a SMTP server or have one that requires authentication, leave the SMTP server as localhost and you can change it later. Click next.

wamp-php-mail-setup

Now we are ready to launch WampServer. Select Launch WampServer 2 now and click finish.

Notice a icon in your system tray.

wamp-icon

Clicking on this icon lets you easily manage Apache, MySQL, and PHP with easy access to important directories and configuration files. It also allows to to stop and start each service or all at once. Especially notice the ‘www directory’ as this is where you can begin to upload your website.

Wamp 2 also includes phpMyAdmin and SQLiteManager which are very useful web applications for managing your MySQL databases.

wamp-menu

Conclusion and further reading

WAMP is a great tool that simplifies the process of installing a web server on your windows computer.

Now that all the server software is installed you can start installing web scripts such as Wordpress, Zencart, and Drupal just to name a few.

del.icio.us Digg Facebook Google reddit SlashDot StumbleUpon Technorati

Installing MySQL 5 on PHP 5 on Windows

December 18, 2008 by admin  
Filed under MySQL, Tutorials

This tutorial explains how to install MySQL server and get it to work with PHP.

MySQL is a free database management system that is used by the majority of web applications today. You can install MySQL by itself, but much of its usefulness comes from using it together with PHP.

This tutorial assumes you have already installed and configured Apache web server and PHP.

Start off by downloading MySQL community server from the official website.

download-mysql-link

Choose the Windows download (Windows x64 if applicable) and select the “pick a mirror” for Windows ZIP/Setup.EXE.

You will be prompted to register with MySQL, you can skip that by clicking the “No thanks” link underneath.
mysql-download-nothanks

Select the mirror closest to you and download.

Once downloaded, extract the setup.exe file and run.
mysql-install-welcome

Next you will be prompted to choose the installation type. For this tutorial we will choose typical, which contains all the files and features you should need. Custom lets you pick and choose which items to install and complete includes files that MySQL developers may need. Click next.
mysql-install-type

Now click install.
mysql-install-copying-files

Some more information about MySQL will appear, click next.

After MySQL is done installing we will need to configure our MySQL server. Click finish to start the configuration wizard.
mysql-install-configure-now

At The configuration welcome screen, click next
mysql-configure-welcome

You will be prompted to choose a configuration type. For this tutorial we will use the standard configuration. The detailed configuration is for setting up servers for specific purposes to increase performance. Click next.
mysql-configure-type

Next a dialog will prompt the user to install MySQL as a service, this means that MySQL server will run even if no one is logged on (For example, f the computer is sitting at the login screen). It also asks whether to include the bin directory in the Windows path. It is highly recommended you check this option as it makes running MySQL commands from the command line much easier (otherwise you have to change to the MySQL bin directory every time).
mysql-configure-service

Next you will set a password for the root account. Make sure the “Modify Security Settings” checkbox is checked and enter a password. This is the password you have to supply any time you want to connect to MySQL. It is recommended you not create an anonymous account for security reasons. Click next.
mysql-configure-account-pw

Now we are ready to apply the configuration settings, click execute. If you have Antivirus or firewall software installed, you may be prompted to allow MySQL to use this port, allow.
mysql-configure-firewall

Once completed, MySQL is installed and ready to use. However, PHP may not yet be configured to use MySQL. To test whether it is, open up notepad and type the following lines of code

$con = mysql_connect('localhost', 'root', 'yourpassword');
if (!$con)
die('Could not connect: ' . mysql_error());
}
else
{
echo “It Works”;
}
?&gt;

mysql-test-script

Make sure “All files” is selected as notepad likes to save everything with a .txt extension if you have text file selected.
mysql-save-testscript

Save the file as testmysql.php and save it in the document root for your web server (ex: htdocs in the apache install directory). Make sure your web server is running and navigate your browser to http://localhost/testmysql.php.

If you see “It works” on the page, then everything is setup and we are done!
If you see the actual code then PHP is not configured correctly for Apache.
If you see a “Could not connect” message, it likely means you mistyped your password or the MySQL service is not running.
If you see a blank page, it means that PHP has not been configured to work with MySQL.

If you see the blank page, it means you did not check the MySQL item when installing PHP (it is not enabled on the default installation). If this is the case, we have a few more steps to configure PHP.

Open the php.ini file located in your PHP installation directory (ex: C:\Program Files\PHP\php.ini) in notepad or any text editor. Search for the line ‘Dynamic Extensions’ and below that add following line

extension=php_mysql.dll

mysql-php-enable-extension
Make sure to save the file.

Go to the download section of the official PHP download page. Download the PHP 5.x zip package (not the installer). Once downloaded open the zip file and find two DLL files: libmysql.dll in the main directory of the zip file and php_mysql.dll in the ext directory.
mysql-php-extention

mysql-php-lib-file

Copy both files into your PHP install directory (this is the default PHP extensions directory, search for the line ‘extension_dir’  in your php.ini file to verify where your extension directory is located).

Now that both DLLs are copied and the extension is enabled in the php.ini configuration file, restart Apache either from the icon in the system tray or from the services manager in the control panel.

Try to open the testmysql.php page in your browser again. If you still see a blank page, make sure you followed all the steps and that you copied the DLL files into the right extension directory. If you are still having problems, look at the Apache error log in the Apache logs directory (ex: C:\Program Files\Apache Software Foundation\Apache2.2\logs\error.log).

Conclusion and further reading.

Apache, PHP, and MySQL together form a powerful combination. With the three, you can create powerful web applications without any expensive commercial tools. Not only that, but having the three allows you to install useful web applications such as Wordpress, Drupal, and Zencart.

For more information on programming with PHP and MySQL check out our PHP programming tutorials.

del.icio.us Digg Facebook Google reddit SlashDot StumbleUpon Technorati

Installing PHP 5 for Apache on Windows

December 17, 2008 by admin  
Filed under PHP, Tutorials

This tutorial walks through the process of installing PHP 5 on Apache for Windows. This tutorial assumes you have already installed Apache web server, if you have not then please consult our Installing Apache section.

First, download the latest version of PHP from the official website. You can install PHP from the Zip archive but for this article we will use the .exe installer.

Scroll down to the Windows Binaries section of the download page. The non-thread-safe download has to do with some compatibility issues between Windows and Unix based platforms. The non-thread-safe download offers better performance but can cause compatibility issues with some add-ons. For this tutorial, download the PHP 5.x installer

Read more

del.icio.us Digg Facebook Google reddit SlashDot StumbleUpon Technorati