0
$conn = mysql_connect('localhost', 'root', 'xyvz5j');
mysql_select_db('rata2', $conn);

How can I do so this so that it won't print a lot of garbage like "Failed to connect" or something (if there's a MySQL error)?

5 Answers 5

3

One person's "garbage" in another's "informative error message" :)

I would recommend not suppressing them with @ but instead have your production server configured to not display error messages at all. You can have them go to a file for periodic review. However, your staging/development systems should be set to output everything, errors, warnings, notices, the lot.

See the error_reporting configuration directive for details.

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

Comments

1

Put an at symbol in front of the calls.

$conn = @mysql_connect('localhost', 'root', 'xyvz5j');
@mysql_select_db('rata2', $conn);

2 Comments

@Gumbo, I'm not sure what you mean by that. mysql_connect issues an warning when there are connection problems.
@Ionut G. Stan: I was wrong. mysql_connect does report a warning when it fails.
1

Just check what value mysql_connect returned before using it:

$conn = mysql_connect('localhost', 'root', 'xyvz5j');
if (!is_resource($conn)) {
    // error
} else {
    mysql_select_db('rata2', $conn);
}

But the warning for a failed connection for mysql_connect cannot be avoided in this way. But you can disable display_errors so that the error is not shown.

Comments

0

The @-symbol will supress the errors completely, but if you want to print out that something is wrong, do this:

$conn = mysql_connect('localhost', 'root', 'xyvz5j') or die("Connection to MySQL failed");
mysql_select_db('rata2', $conn) or die("MySQL database not found");

Comments

-1

You could set an error_reporting level of 0. Mandatory in production code, ugly when developing. So have separate values for the two environments.

4 Comments

-1 Even in the production environment errors should be reported and logged.
Gumbo, where did you get that I recommend it in development?
@Ionut G. Stan: Setting error_reporting to 0 is like closing the eyes and saying there are no errors. And that’s no option.
No kidding? That's why you recommend it in your answer too?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.