tags:

views:

67

answers:

5
$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)?

+1  A: 

Put an at symbol in front of the calls.

$conn = @mysql_connect('localhost', 'root', 'xyvz5j');
@mysql_select_db('rata2', $conn);
James Skidmore
@Gumbo, I'm not sure what you mean by that. `mysql_connect` issues an warning when there are connection problems.
Ionuț G. Stan
@Ionut G. Stan: I was wrong. `mysql_connect` does report a warning when it fails.
Gumbo
A: 

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");
sshow
+3  A: 

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.

Paul Dixon
A: 

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

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

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.

Gumbo