PHP Variables not existing and forms

By Steven Lloyd Watkin, Thursday 31st July 2008 10:36 am

I came across something I wasn’t aware of today that is very handy…. the error control operator ‘@’ in PHP.

So for some background to how I came across this problem, in my web applications I tend to use the same form to insert data into a mySQL database. If I have an some sort of ‘id’ number set via a GET variable then that triggers a load from the database, otherwise I’m adding new data.

In my form elements I often set the value of the form field to something like <?=$data['fieldValue'];?> this works fine when loading data but when I’m inserting new data I get the form filled in as follows (note on my login or when I’m testing I have error reporting set to E_ALL so I can make sure everything is running correctly):

Notice: Undefined variable: data in /home/public_html/dataEdit.php on line 69

So what I eventually ended up doing was writing longer (uglier) code which said, <? if (isset($data['fieldValue'])) { echo $data['fieldValue']; } ?>. Not exactly great

Then I stumbled across the error control operator in PHP, by simply placing an ‘@’ symbol before an operator (basically anything that can return a result) the above problem is solved. For example I can now make my for value parameter <?=@$data['fieldValue'];?>. If the variable is not set (i.e. an error would be generated) then the error is suppressed.

Note: Using the ‘@’ symbol can supress major errors and hide the fact that part of your site isn’t running correctly, so be careful!

Leave a Reply

Panorama Theme by Themocracy

10 visitors online now
10 guests, 0 members
Max visitors today: 42 at 02:50 am UTC
This month: 42 at 11-03-2010 02:50 am UTC
This year: 42 at 11-03-2010 02:50 am UTC
All time: 42 at 11-03-2010 02:50 am UTC