Check whether a mysql_connect() failed or not?
Hey i'm trying to find out whether my sql query failed or not. I want it so if it does fail redirect to form page using the code below:
$checkconnection = mysql_connect('localhost', $dbuser, $dbpass)
or die();
if(!$checkconnection)
{
$_SESSION['errormsg'] = "<div style='padding-left: 50px;color:#FF0000'>Cannot connect to specfied database!</div>";
header("Location: install.php");
}else{
echo('Connection Successful!');
}
using that all it says is this:
开发者_JAVA百科Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'nzcraftn_admin'@'localhost' (using password: YES) in /home/nzcraftn/public_html/phishnet/install/install_submit.php on line 17
Try this one
$checkconnection = @mysql_connect('localhost', $dbuser, $dbpass)
it will hide default error and trigger your own
The return value of mysql_connect
being false only indicates failure. If it returns FALSE
, the or die()
expression will exit the php script. That's the reason why you don't sea any of it's output.
Remove the or die()
command, and display the actual error in your if( !$checkconnection )
clause. The reported error can be retrieved using mysql_error()
.
It's only displaying the warning because your or die()
isn't outputting anything (empty parameter list). Try this instead:
<?php
//Start the session
session_start();
//Do the conntection
$checkconnection = @mysql_connect('localhost', $dbuser, $dbpass);
//Check if it's valid
if(!$checkconnection) {
//Add it up to the session, and redirect
$_SESSION['errormsg'] = "<div style='padding-left: 50px;color:#FF0000'>Cannot connect to specfied database!</div>";
session_write_close();
header("Location: install.php");
exit();
} else{
//Yay
echo('Connection Successful!');
}
?>
The answer by genesis just supresses the warning, but still might work
If you want it 'clean' you can try/catch the error:
(directly from the comments on php.net/mysql_connect:
// Assign variables
global $db_connection, $db_server, $db_database, $db_username, $db_password;
$db_server = $server;
$db_database = $database;
$db_username = $username;
$db_password = $password;
// Attempt connection
try
{
// Create connection to MYSQL database
// Fourth true parameter will allow for multiple connections to be made
$db_connection = mysql_connect ($server, $username, $password, true);
mysql_select_db ($database);
if (!$db_connection)
{
throw new Exception('MySQL Connection Database Error: ' . mysql_error());
}
else
{
$CONNECTED = true;
}
}
catch (Exception $e)
{
echo $e->getMessage();
}
精彩评论