Better way to write php code – part 2

With the help of an example i would explain a very common but erroneous approach new php developers seem to follow (i have seen some ‘old’ ones repeating the same error though). Here it is,

Let’s say you want to pass a variable from one page to another page using GET method and retrieving its value in the later. For example you have a link with url http://www.devarticle.in/index.php?article_id=123. The code one would write to get the value of article_id in index.php is

$article_id = $_GET['article_id'];

There is nothing wrong with this code. But, there is one mistake. See what happens when you call index.php page without passing a GET parameter? For example, when you call http://www.devarticle.in/index.php or http://www.devarticle.in/index.php?category_id=12 etc.. If the php notices display is turned on, the page will throw notice something like this:

Notice: Undefined index: article_id in /var/www/html/path/to/file.php on line no #.

Also the additional php code depending upon the value of $article_id down the page, for example mysql queries etc. may throw more errors to mess the page up. To avoid this, just add a check prior to variable assignment, something like this,

if(isset($_GET['article_id']))  {
$article_id = $_GET['article_id'];
}

where you check whether an ‘article_id’ named index is set within your GET request array and if it is set, assign its value to $article_id named variable. And your php parser will like it! The same approach is applied to POST, REQUEST or SESSION variables as well. For example, you may have set a SESSION variable somewhere and when you want to get its value in a different page it is the best thing to write like this:

if(isset($_SESSION['some_value']))  {
$some_value = $_SESSION['some_value'];
}

I hope this makes sense.

The next thing i would like to share is the use of $_REQUEST global variable which i would share in the next post of this series.

Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *