Codeigniter/PHP check if can connect to database - php

I'd like to backup my read replica(i.e., slave) database with my master database but this simple boolean I did failed:
$config['hostname'] = "myReadReplicaDatabase.com";
//...$config['other_stuff']; other config stuff...
$db_obj=$CI->load->database($config, TRUE);
if(!$db_obj){
$config['hostname'] = "myMasterDatabase.com";
$db_obj=$CI->load->database($config, TRUE);
}
After terminating my read replica database I expected the boolean to evaluate to FALSE and the script to then use my master database. Unfortunately, instead I got the following PHP error:
Unable to connect to your database server using the provided settings.
Filename: core/Loader.php
All i want is for the connection to return true or false, does anyone know how to do this in Codeigniter?

My question was answered on this thread on Codeigniter forums.
The key is to not autoinitialize the database:
$db['xxx']['autoinit'] = FALSE;
To suppress errors it you can set this
$db['xxx']['db_debug'] = FALSE;
Then in your code that checks the db state, check TRUE/FALSE of the initialize() function:
$db_obj = $this->database->load('xxx',TRUE);
$connected = $db_obj->initialize();
if (!$connected) {
$db_obj = $this->database->load('yyy',TRUE);
}
Here is my entire config file for future reference: https://gist.github.com/3749863.

when you connect to database its returns connection object with connection id on successful condition otherwise return false.
you can check it to make sure that database connection is done or not.
$db_obj=$CI->load->database($config, TRUE);
if($db_obj->conn_id) {
//do something
} else {
echo 'Unable to connect with database with given db details.';
}
try this and let me know, if you have any other issue.

I test all I found and nothing wokrs, the only way I found was with dbutil checking if database exists, something like this:
$this->load->database();
$this->load->dbutil();
// check connection details
if( !$this->dbutil->database_exists('myDatabase'))
echo 'Not connected to a database, or database not exists';

Based on what was said here:
Codeigniter switch to secondary database if primary is down
You can check for the conn_id on the $db_obj
if ($db_obj->conn_id === false) {
$config['db_debug'] = true;
$config['hostname'] = "myMasterDatabase.com";
$db_obj=$CI->load->database($config, TRUE);
}
This should work.

try {
// do database connection
} catch (Exception $e) {
// DO whatever you want with the $e data, it has a default __toString() so just echo $e if you want errors or default it to connect another db, etc.
echo $e->getMessage();
// Connect to secondary DB.
}
For those who downvoted me, you can do this. Exception will catch PDOException.
try {
$pdo = new PDO($dsn, $username, $password);
} catch(PDOException $e) {
mail('webmaster#example.com', 'Database error message', $e->getMessage());
// and finally... attempt your second DB connection.
exit;
}

$readReplica = #$CI->load->database($config, TRUE); // ommit the error
if ($readReplica->call_function('error') !== 0) {
// Failed to connect
}
Im not sure about the error code (not sure if its int/string) and don't have CI nearby to test this out but this principle should work

$this->load->database();
print_r($this->db);

Its work for me
$config['xxx'] = xx;
...
$config['db_debug'] = false;
$db_obj = #$this->load->database($config,true);
if(!#$db_obj->initialize()){
echo "Unable to connect database";
die;
}

Related

Database connection and die issue

if(DB::connection()->getDatabaseName()){
$data = User::get(['id','first_name','last_name']);
return View::make('index')->with('data',$data);
}
else{
$request->session()->put('error','Could not connect to the database. Please check your configuration.');
return view::make('errors.503');
}
My else part is not working while DB is not connect. How to handle all DB connection and die exception in laravel 5.2
DB::connection()->getDatabaseName() checks the name from your configuration, that must be the reason why always evaluates to true
Try instead DB::connection()->getPdo();, it will throw an exception (use try/catch) if fails.
edit:
try {
DB::connection()->getPdo();
$data = User::get(['id','first_name','last_name']);
return View::make('index')->with('data',$data);
} catch (\PDOException $e) {
$request->session()->put('error','Could not connect to the database. Please check your configuration.');
return view::make('errors.503');
}

Connecting to Oracle database from PHP

I have an Oracle database that I am trying to connect to.
For some reason when I try the following code:
<?php
include "header.php";
// simply attempt to connect to the database
/* If you are connecting to the Oracle database, the credentials are as follows:
* Username: ********
* Password: ********
* Hostname: **********
* Port: 1521
* Service name: ***********
*/
$oracleConnect = true;
if ($oracleConnect)
{
echo 'Attempting connection...<br>';
$connection = null;
try
{
$connection = oci_connect('user',
'pass',
'user#//hostname:1521/dbname');
}
catch (Exception $e)
{
echo $e->getMessage();
}
if (!$connection)
{
echo '<p>Something is wrong.</p>';
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// if the connection has been established
else
{
// tell the user and close it (this is a test)
echo 'Connection established!!';
oci_close($connection);
}
}
else
{
$connection = new mysqli('host', 'user', 'password', 'database');
echo ($connection) ? 'Database connection successful!' : 'Could not connect.';
}
include "footer.php";
?>
When I try the above code, I get the "Attempting connection..." to print, but nothing else. It is supposed to print something else regardless. What could possibly be going wrong?
I think the problem is the user# part of your connection string. I dont think thats necessary as oci_connect has a user name parameter. I could be wrong, ive never used oracle from php before, but the docs on oci connections would also seem to indicate that:
To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. From Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.
Also oci_connect does not throw an exception as far as i can tell so your try/catch is useless unless you planned on throwing your own when it returns false.

Codeigniter alternate database connection if server down

I want to use a raw php code in Codeigniter for alternate database connection my raw php code is:
$db = mysql_connect('remote_server', 'username', 'password'); if(!$db){
$db = mysql_connect('localhost', 'username', 'password') ; }
to connect to a backup server if the remote mysql server is down for some reason.
Has anyone done this kind of thing with CodeIgniter? If so, would you mind sharing code or ideas?
UPDATE:
just figured out a better approach.
suppose you have 2 database configuration in database.php, one is the default, the other is the backup
i.e
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'temp_test1';
//.......
$db['backup']=$db['default'];
$db['backup']['hostname'] = 'localhost1';
$db['backup']['username'] = 'root';
$db['backup']['password'] = '';
$db['backup']['database'] = 'temp_test1';
now, add this to the end of the database.php file
//check to see if you can connect
$conn=#mysql_connect($db['default']['hostname'],$db['default']['username'],$db['default']['password']);
if($conn) //check to see if it's connecting, if it is close this connection
{
mysql_close($conn);
}
else{ //if it isnt
$db['default']=$db['backup']; //replace the default credentials with the backup credentials
}
OLD POST:
there are a lot of approaches you can take.
Your you can check if a particular connection is open via this mysql_ping(), i.e
$conn=mysql_connect(...);
if(mysql_ping($conn)){...};
so you can use this method to decide which database to choose.
For codeigniter, one approach (which is a rather bad one I would say, but an approach none the less), is to mess with the system files. In DB_Driver, in this portion of the code:
$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
if ( ! $this->conn_id)
{
log_message('error', 'Unable to connect to the database');
if ($this->db_debug)
{
$this->display_error('db_unable_to_connect');
}
return FALSE;
}
is where it tries to connect and checks if connection was successful, and if not gives the error.
I'm not sure how you do exception handling in CI, but basically you should handle an exception and connect to a different database.
Since I dont know exception handling, say I create a database_backup.php file the config folder hostname, username, password, and database variable. Then I would change the code to this
$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
if ( ! $this->conn_id) //oops, first connection failed
{
//no problem, change the credentials of the database to our backup credentials
$ci=&get_instance();
$ci->load->config('database_backup');
$this->username=$ci->config->item('username');
$this->password=$ci->config->item('password');
$this->database=$ci->config->item('database');
$this->hostname=$ci->config->item('hostname');
//try to connect to database once more
$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
// No connection resource STILL?nothing we can do now, throw an error
if ( ! $this->conn_id)
{
log_message('error', 'Unable to connect to the database');
if ($this->db_debug)
{
$this->display_error('db_unable_to_connect');
}
return FALSE;
}
}
take a look at system/database/drivers/mysql/mysql_driver.php
find the function function db_connect() [or function db_pconnect() depending upon which one you using]
there is the connection code:
return #mysql_connect($this->hostname, $this->username, $this->password, TRUE);
change the logic to suit your need.
by the way, prefere to use the PDO driver instead as by default, codeigniter uses mysql_* of whose depreciation process started.

Difference between mssql_connect and sqlsrv_connect

I have just changed the connection driver (extension) from mssql_connect to work with sqlsrv_connect. Unfortunately things do not seem to work as I wanted. I'd appreciate if someone can tell me what’s wrong and how can I fix it.
Code excerpt:
//a oracle DB moudle with a generic functions such as
//db_connect() db_query()
/// turn on verbose error reporting (15) to see all warnings and errors
error_reporting(15);
//generic DB operations
// Global record . for using in
$curr_rec = NULL;
function dbok($res)
{
if($res==false){
echo "DB error: "."FIXME need error mesg"."\n";
exit;
}
return $res;
}
function db_now_expr()
{
return "getdate()";
}
function db_is_connected($dbh)
{
return $dbh>0;
}
function ensure_connected($dbh)
{
if(!db_is_connected($dbh)) die("DB is not connected, operation failed");
//echo "DEBUG: hdb=$dbh";
}
//connect to given database
//return handler to DB
function dbo_logon($dbserver,$dbname)
{
$tsql = ??????? ====>>> what should i put here????
$dbserver = "computername\SQLEXPRESS";
$dbname = MY_Database_name;
$connectionOptions = array("Database"=>"BULL");
$dbh=dbok(sqlsrv_connect($dbserver, $connectionOptions));
dbok(sqlsrv_query($dbname,$dbh));
$stmt = sqlsrv_query( $connectionOptions, $tsql );
return $dbh;
}
//close DB
function dbo_logoff($dbh)
{
if(!db_is_connected($dbh)) echo("DB disconnect error");
sqlsrv_close($dbh);
}
Here is the original code using mssql_connect:
//a oracle DB module with a generic function such as
//db_connect() db_query()
/// turn on verbose error reporting (15) to see all warnings and errors
error_reporting(15);
//generic DB operations
// Global record . for using in
$curr_rec = NULL;
function dbok($res)
{
if($res==false){
echo "DB error: "."FIXME need error mesg"."\n";
exit;
}
return $res;
}
function db_now_expr()
{
return "getdate()";
}
function db_is_connected($dbh)
{
return $dbh>0;
}
function ensure_connected($dbh)
{
if(!db_is_connected($dbh)) die("DB is not connected, operation failed");
//echo "DEBUG: hdb=$dbh";
}
//connect to given database
//return handler to DB
function dbo_logon($dbserver,$dbuser,$dbpass,$dbname)
{
// $dbh=dbok(mssql_pconnect($dbserver,$dbuser,$dbpass));
$dbh=dbok(mssql_connect($dbserver,$dbuser,$dbpass));
//error_log("connect to [$dbname]".date("His")." \r\n",3,"/tmpbull.log"); //DBEUG DELME
dbok(mssql_select_db($dbname,$dbh));
//dbo_exec($dbh,"alter session set NLS_DATE_FORMAT='dd-mm-yyyy //hh24:mi:ss'");
return $dbh;
}
//close DB
function dbo_logoff($dbh)
{
if(!db_is_connected($dbh)) echo("DB disconnect error");
mssql_close($dbh);
}
Note that I had to change the authentication method from SQL authentication to Windows authentication because sqlsrv_connect uses Windows authentication instead of SQL authentication. Is that right?
I think these two links will help to understand Difference between mssql and sqlsrv
http://blogs.msdn.com/b/brian_swan/archive/2010/03/08/mssql-vs-sqlsrv-what-s-the-difference-part-1.aspx
http://blogs.msdn.com/b/brian_swan/archive/2010/03/10/mssql-vs-sqlsrv-what-s-the-difference-part-2.aspx
Though in short, to quote one of the articles:
The sqlsrv driver is built, maintained, and supported by Microsoft`
and
The mssql driver is a community-built driver.
I’m not sure how recently this driver was updated or maintained as an official PHP extension, but as of the release of PHP 5.3, it is no longer available with PECL. A quick internet search turns up a few places to download the mssql driver, but none of them that I’ve found indicate that the driver is being actively maintained.
Source: http://blogs.msdn.com/b/brian_swan/archive/2010/03/08/mssql-vs-sqlsrv-what-s-the-difference-part-1.aspx
As for your code sample, see below:
$dbserver = "computername\SQLEXPRESS";
$dbname = "BULL";
$connetion = dbo_logon($dbserver,$dbname);
function dbo_logon($dbserver,$dbname) {
$connectionOptions = array("Database"=>$dbname);
$dbh=sqlsrv_connect($dbserver, $connectionOptions);
if(!$dbh){
die("Error in Database connection");
return false;
}
return $dbh;
}
I think this will work for the connection.please note the code is not tested.
"The sqlsrv driver is built, maintained, and supported by Microsoft`" well right now Sep 2014, there is no official release to support php 5.6 last official release is from april 2012. MS style...

PHP Try and Catch for SQL Insert

I have a page on my website (high traffic) that does an insert on every page load.
I am curious of the fastest and safest way to (catch an error) and continue if the system is not able to do the insert into MySQL. Should I use try/catch or die or something else. I want to make sure the insert happens but if for some reason it can't I want the page to continue to load anyway.
...
$db = mysql_select_db('mobile', $conn);
mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'") or die('Error #10');
mysql_close($conn);
...
Checking the documentation shows that its returns false on an error. So use the return status rather than or die(). It will return false if it fails, which you can log (or whatever you want to do) and then continue.
$rv = mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'");
if ( $rv === false ){
//handle the error here
}
//page continues loading
This can do the trick,
function createLog($data){
$file = "Your path/incompletejobs.txt";
$fh = fopen($file, 'a') or die("can't open file");
fwrite($fh,$data);
fclose($fh);
}
$qry="INSERT INTO redirects SET ua_string = '$ua_string'"
$result=mysql_query($qry);
if(!$result){
createLog(mysql_error());
}
You can implement throwing exceptions on mysql query fail on your own. What you need is to write a wrapper for mysql_query function, e.g.:
// user defined. corresponding MySQL errno for duplicate key entry
const MYSQL_DUPLICATE_KEY_ENTRY = 1022;
// user defined MySQL exceptions
class MySQLException extends Exception {}
class MySQLDuplicateKeyException extends MySQLException {}
function my_mysql_query($query, $conn=false) {
$res = mysql_query($query, $conn);
if (!$res) {
$errno = mysql_errno($conn);
$error = mysql_error($conn);
switch ($errno) {
case MYSQL_DUPLICATE_KEY_ENTRY:
throw new MySQLDuplicateKeyException($error, $errno);
break;
default:
throw MySQLException($error, $errno);
break;
}
}
// ...
// doing something
// ...
if ($something_is_wrong) {
throw new Exception("Logic exception while performing query result processing");
}
}
try {
mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'")
}
catch (MySQLDuplicateKeyException $e) {
// duplicate entry exception
$e->getMessage();
}
catch (MySQLException $e) {
// other mysql exception (not duplicate key entry)
$e->getMessage();
}
catch (Exception $e) {
// not a MySQL exception
$e->getMessage();
}
if you want to log the error etc you should use try/catch, if you dont; just put # before mysql_query
edit :
you can use try catch like this; so you can log the error and let the page continue to load
function throw_ex($er){
throw new Exception($er);
}
try {
mysql_connect(localhost,'user','pass');
mysql_select_db('test');
$q = mysql_query('select * from asdasda') or throw_ex(mysql_error());
}
catch(exception $e) {
echo "ex: ".$e;
}
Elaborating on yasaluyari's answer I would stick with something like this:
We can just modify our mysql_query as follows:
function mysql_catchquery($query,$emsg='Error submitting the query'){
if ($result=mysql_query($query)) return $result;
else throw new Exception($emsg);
}
Now we can simply use it like this, some good example:
try {
mysql_catchquery('CREATE TEMPORARY TABLE a (ID int(6))');
mysql_catchquery('insert into a values(666),(418),(93)');
mysql_catchquery('insert into b(ID, name) select a.ID, c.name from a join c on a.ID=c.ID');
$result=mysql_catchquery('select * from d where ID=7777777');
while ($tmp=mysql_fetch_assoc($result)) { ... }
} catch (Exception $e) {
echo $e->getMessage();
}
Note how beautiful it is. Whenever any of the qq fails we gtfo with our errors. And you can also note that we don't need now to store the state of the writing queries into a $result variable for verification, because our function now handles it by itself. And the same way it handles the selects, it just assigns the result to a variable as does the normal function, yet handles the errors within itself.
Also note, we don't need to show the actual errors since they bear huge security risk, especially so with this outdated extension. That is why our default will be just fine most of the time. Yet, if we do want to notify the user for some particular query error, we can always pass the second parameter to display our custom error message.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.
$sql = "INSERT INTO customer(FIELDS)VALUES(VALUES)";
mysql_query($sql);
if (mysql_errno())
{
echo "<script>alert('License already registered');location.replace('customerform.html');</script>";
}
To catch specific error in Mysqli
$conn = ...;
$q = "INSERT INTO redirects (ua_string) VALUES ('$ua_string')";
if (mysqli_query($conn, $q)) {
// Successful
}
else {
die('Mysqli Error: '.$conn->error); // Show Error Complete Description
}
mysqli_close($conn);
Use any method described in the previous post to somehow catch the mysql error.
Most common is:
$res = mysql_query('bla');
if ($res===false) {
//error
die();
}
//normal page
This would also work:
function error() {
//error
die()
}
$res = mysql_query('bla') or error();
//normal page
try { ... } catch {Exception $e) { .... } will not work!
Note: Not directly related to you question but I think it would much more better if you display something usefull to the user. I would never revisit a website that just displays a blank screen or any mysterious error message.
$new_user = new User($user);
$mapper = $this->spot->mapper("App\User");
try{
$id = $mapper->save($new_user);
}catch(Exception $exception){
$data["error"] = true;
$data["message"] = "Error while insertion. Erron in the query";
$data["data"] = $exception->getMessage();
return $response->withStatus(409)
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}
if error occurs, you will get something like this->
{
"error": true,
"message": "Error while insertion. Erron in the query",
"data": "An exception occurred while executing 'INSERT INTO \"user\" (...) VALUES (...)' with params [...]:\n\nSQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: \"default\"" }
with status code:409.

Categories