PHP Variables not existing and forms

By , 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!

Liked this post? Follow this blog to get more. 

Leave a Reply

You must be logged in to post a comment.

Panorama Theme by Themocracy

1 visitors online now
0 guests, 1 bots, 0 members
Max visitors today: 6 at 03:27 am UTC
This month: 15 at 10-10-2017 02:55 pm UTC
This year: 45 at 02-01-2017 10:28 pm UTC
All time: 130 at 28-03-2011 10:40 pm UTC