Testing a database connection without a flare-up by throwing a fit, can this be done?
I've just finished my first release of the automailer, a program I've been working on for a while. I have to finish recording the installer. Its job is to rewrite codigniter configuration from templates. I have a read / write job, but I want to be able to validate the server credentials given by the user without coding, throwing a system error if they are wrong. Is there a function other than mysql_connect that I can use to test the connection that will return true or false and not make the codeignign appropriate?
This is what I have
function _test_connection(){
if(mysql_connect($_POST['host'], $_POST['username'], $_POST['password'], TRUE))
return TRUE;
else
return FALSE;
}
Codigniter doesn't like it and throws a system error.
<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
<h4>A PHP Error was encountered</h4>
<p>Severity: Warning</p>
<p>Message: mysql_connect() [<a href='function.mysql-connect'>function.mysql-connect</a>]: Unknown MySQL server host 'x' (1)</p>
<p>Filename: controllers/install.php</p>
<p>Line Number: 57</p>
</div>
I would prefer not to disable error reporting.
a source to share
You can use @operator to suppress the error that PHP should throw .
function _test_connection(){
$db = @mysql_connect($_POST['host'], $_POST['username'], $_POST['password'], TRUE);
if($db)
return TRUE;
else
return FALSE;
}
Please note that it is not recommended to use it most of the time, as it will hide any errors, even critical ones.
Check out the Error Handling and Logging sections in the PHP manual to learn more.
a source to share
This is not the best solution as it uses the built-in mysql php connection function. DOESNT'S NEXT WORK! however since codeigniter needs to work to test user database input when installing the app.
$config['hostname'] = "localhost";
$config['username'] = "username";
$config['password'] = "password";
$config['database'] = "database_name";
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = FALSE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";
if($this->load->database($config)==TRUE){
return TRUE;
}else{
return FALSE;
}
a source to share