4

Possible Duplicates:
Reference - What does this symbol mean in PHP?
What does @ mean in PHP?

I have a line in my code which looks like this:

@mysql_select_db($dbname) or die( "Error: Unable to select database");

It works, but I want to know what the @ does and why it is there.

7
  • 2
    In a great quote I saw recently, "it prevents you from finding out what's wrong with your program". I think it was Gordon... Commented Dec 16, 2010 at 11:33
  • @ElYobo dont think it was me, but there is much truth in it Commented Dec 16, 2010 at 12:30
  • 1
    @Gordon, you should have stayed quiet and took the credit then ;) It was somewhere here on SO, but I can't seem to find it now. Commented Dec 16, 2010 at 12:37
  • 2
    "@Gordon, you should have stayed quiet..." Given the question, I find this funny. Commented Dec 16, 2010 at 12:43
  • 2
    @Aether hehe, yeah, but I have scream enabled by default ;) Commented Dec 16, 2010 at 12:46

3 Answers 3

13

The @ symbol suppresses any errors and notices for the expression it precedes.

See this reference: PHP Error Control Operators

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

Sign up to request clarification or add additional context in comments.

Comments

2

In this case, the @ will suppress the regular PHP database connection error (which may contain sensitive information). In case of a connection error, the "or die" part will be executed, failing with a generic error message. The line is probably copied from a "quick and dirty" example.

Using the error suppression operator @ is considered bad style, especially when other forms of error handling are missing. It complicates debugging - how can you find out about in error without any indication that it occured? In a production system it's better to log all errors to a file and suppress the rendering of errors on the page. You could do that in the php.ini file or (if you are on a shared host and not allowed to make config changes) with the following code.

ini_set('display_errors', false); ini_set('log_errors', true); ini_set('error_log', '/var/log/apache/php-errors.log'); 

2 Comments

@ will suppress every error, not just database connection errors.
Thanks, I have edited my answer to reflect this.
1

It suppresses all error output. Generally, you shouldn't use it unless you have a good reason. I don't know why it is used in the example you posted, or why die() is used. The error should be caught and processed accordingly. The select may fail for a number of reasons, some perhaps recoverable. Like no connection to the database established.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.