Database connection and die issue - php

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');
}

Related

If statement not working properly while data gets inserted

I have created a function which takes three parameters.
My function is simple, it connects to database using pdo but when I call it the data gets inserted, but when I wrap the function inside variable, the if statement doesn't work as expected. My function is just like this
function connect($data,$username,$password){
try { $connect =new PDO($data,$username,$password);
$connect->setAttribute(PDO::ATTR_ERRMODE, ERRMODE_EXCEPTION);
$connect->exec("INSERT INTO data(fname,lname,uname, password) VALUES('raashid','din','dar','wow')");
} catch( Exception $e) {
echo "error occurred". $e->get messages();
}
return;
}
$db =connect("mysql:host=localhost","root","pass");
if($db){
echo "Yes connected";
} else {
echo " not connected";
}
I don't know why if conditional shows not connected while data gets inserted.
Any help will be appreciated.
Empty return; is the same as return null;. And null is considered falsy value, so if($db){ is false and you see the relevant message.
So, you should return another value from your function. For example true when everything is ok and false when exception occured, for example:
function connect($data,$username,$password){
try {
$connect = new PDO($data,$username,$password);
$connect->setAttribute(PDO::ATTR_ERRMODE, ERRMODE_EXCEPTION);
$connect->exec("INSERT INTO data(fname,lname,uname, password) VALUES('raashid','din','dar','wow')");
return true;
} catch( Exception $e) {
echo "error occurred". $e->getMessage();
return false;
}
}

Using Exceptions to control application flow

I am currently writing a web app in PHP and have decided to use exceptions (duh!).
I could not find an answer to whether putting try and catch blocks in all functions would be considered bad code.
I am currently using Exceptions to handle Database errors (Application errors are handled via a simple function which just adds them to an array and then they are displayed to the user). The try blocks are placed on all functions which require a database connection.
The code in question is:
public function db_conn_verify()
{
if(!isset($this->_mysqli)){
throw new Exception("Network Error: Database connection could not be established.");
} else {
return Null;
}
}
And an example function using this code:
public function get_users() {
try {
$this->db_conn_verify();
//Rest of function code
return True;
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
return False;
}
}
Also would it be better to extend the Exception class and then use that new Exception class to handle application errors?
Thanks
I suggest to you to use something like this:
public function get_users() {
try {
if( !isset($this->_mysqli) ) {
throw new Exception("Network Error: Database connection could not be established.");
}
//Rest of function code
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
}
}
I prefer to use my exends of Exception, but is the same. For exdending exception you can see the PHP documentation to Example #5
EDIT: For an immediate use of try-catch on database connection error you can try this:
try{
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
throw new Exception("Network Error: Database connection could not be established.");
}
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
}

libcouchbase connection errors

Couchbase keeps complaining that I don't have a connection to Couchbase:
2013-10-28T11:15:46.580320-07:00 hoot77 apache2[30455]: PHP Warning: There is no active connection to couchbase in /ebs1/www/src/core/components/In/Couchbase/Bucket.php on line 112
The following is the piece of code that is trying to run, its a simple set.
*/
public function set($key, $doc, $try = 0) {
// Make sure designDoc and dataView are set
if(empty($this->designDoc) && empty($this->dataView)) {
throw new In_Exception('Missing Design Doc and/or View name for Couchbase', 400);
}
try {
$results = $this->cb->set($key, $doc);
} catch(CouchbaseLibcouchbaseException $e) {
// Connection not active, try to rebuild connection and query again
// Log stats on exception
Statsd::increment("web.Couchbase.Exception.LibCouchbaseException.{$this->instanceKey}");
Logger::error("LibCouchbaseException on {$this->instanceKey}: {$e->getMessage()}");
// Try to reconnect and query up to twice
$try++;
if($try <= 2) {
$this->rebuildConnection();
return $this->set($key, $doc, $try);
} else {
// Fail if we've already tried twice
throw new In_Exception('Could not connect to Couchbase', 500);
}
} catch(CouchbaseException $e) {
// Catch general exception, try to determine cause
// Log stats on exception
Statsd::increment("web.Couchbase.Exception.CouchbaseException.{$this->instanceKey}");
Logger::error("CouchbaseException on {$this->instanceKey}: {$e->getMessage()}");
// Throw exception if design document or view not found
if($this->getExceptionCode($e->getMessage()) == 404) {
throw new In_Exception('Design Document, or View not found in Couchbase', 404);
} else {
throw new In_Exception('Error with Couchbase, try again.', 500);
}
}
// Success, return results
Statsd::increment("web.couchbase.{$this->instanceKey}.success");
return $results;
}
The line that its complaining about is:
$results = $this->cb->set($key, $doc);
You can see that my quick solution was to try to reconnect up to twice on failure, but that doesn't seem to be helping at all, the errors still persist in great numbers.
It's actually not catching the exceptions and reporting them consistently either, which is annoying, because PHP is throwing these as warnings, not exceptions.
Let me know if you have any suggestions as to how to solve this, it would be greatly appreciated. Thanks!

Test if connection is an error

I am using this script here and it does not always want to connect to the server I set it to. When it doesn't, it'll show an error "Failed to receive status". I'm wondering how can I test to see if this happens and put it into an if statement?
For example:
if (isError) return false;
Here is the part which checks for the error or not in the script:
if( !$Data )
{
throw new MinecraftQueryException( "Failed to receive status." );
}
Just use try ... catch block. But make sure you are logging the exception message. It'll be helpful for future investigation.
try
{
$Query = new MinecraftQuery( );
// .. do mine craft connection
$Query->Connect( '...', 25565 );
print_r( $Query->GetInfo( ) );
} catch(MinecraftQueryException $mqe){
// log $mq->getMessage() for future investigation
return false;
}
You'll want to surround the Connect call inside a try/catch block in order to catch the exception, and then put the failure code inside the catch block. You can read more about exceptions in the PHP manual:
try {
$query->Connect();
} catch(MinecraftQueryException $exception) {
return false;
}

Codeigniter/PHP check if can connect to database

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;
}

Categories