database error keeps radomly appearing in codeigniter - php

I have a working CodeIgniter code but once in a while i get an error.
Unable to connect to your database server using the provided settings.
Filename: core/Loader.php
Line Number: 347
It only pops up once in a while but it is so annoying.
Anything i can do about this?
Because it was asked here is the Loader code surrounding the error
public function database($params = '', $return = FALSE, $active_record = NULL)
{
// Grab the super object
$CI =& get_instance();
// Do we even need to load the database class?
if (class_exists('CI_DB') AND $return == FALSE AND $active_record == NULL AND isset($CI->db) AND is_object($CI->db))
{
return FALSE;
}
require_once(BASEPATH.'database/DB.php');
if ($return === TRUE)
{
return DB($params, $active_record);
}
// Initialize the db variable. Needed to prevent
// reference errors with some configurations
$CI->db = '';
// Load the DB class
$CI->db =& DB($params, $active_record);
}

Problem was my host not being able to handle alot of database requests. We are working on getting a better connection

Related

Non-static method should not be called statically in Kohana 2.3.4

i've moved my Kohana 2.3.4 installation to a new hosting with php7 (probably that's a root of the issue) and now i am getting the following error:
Uncaught PHP Error: Non-static method AdminHook::menu_tree() should not be called statically in file system/core/Event.php on line 209
Here's my Event.php around line 209 (call_user_func($callback); is at line 209):
public static function run($name, & $data = NULL)
{
if ( ! empty(self::$events[$name]))
{
// So callbacks can access Event::$data
self::$data =& $data;
$callbacks = self::get($name);
foreach ($callbacks as $callback)
{
call_user_func($callback); // LINE 209
}
// Do this to prevent data from getting 'stuck'
$clear_data = '';
self::$data =& $clear_data;
}
// The event has been run!
self::$has_run[$name] = $name;
}
And here's the AdminHook class:
class AdminHook {
public function menu_tree(){
$session = Session::instance();
if(isset($_GET['_ml']) AND $_GET['_ml'] == 1) {
$session->set('menuLink', 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
//url::redirect(url::current());
}
global $menuLink;
$menuLink = $session->get('menuLink');
}
}
If i set menu_tree function to static, i get the following error:
Uncaught PHP Error: Declaration of Menu_Model::validate(array &$array, $save = false) should be compatible with ORM_Core::validate(Validation $array, $save = false) in file application/models/menu.php on line 18
I've been trying to find a solution for the next couple of days, but can't seem to find one. Any help is highly appreciated!
Errors are not related to each other. By simply setting that method as static, php goes to showing the next error.
You have bad Menu_Model declaration. It mut be compatible with ORM_Core::validate
Menu_Model::validate(/*bad: array & */ Validation $array, $save = false)

Database error on website

I got this error trying to access our SCADA website:
A Database Error Occurred
Unable to connect to your database server using the provided settings.
Filename: core/Loader.php
Line Number: 341
I scanned into the Loader.php file and on line 341 found this code:
$CI->db =& DB($params, $active_record);
This is the complete block with the error code:
public function database($params = '', $return = FALSE, $active_record = NULL)
{
// Grab the super object
$CI =& get_instance();
// Do we even need to load the database class?
if (class_exists('CI_DB') AND $return == FALSE AND $active_record == NULL AND isset($CI->db) AND is_object($CI->db))
{
return FALSE;
}
require_once(BASEPATH.'database/DB.php');
if ($return === TRUE)
{
return DB($params, $active_record);
}
// Initialize the db variable. Needed to prevent
// reference errors with some configurations
$CI->db = '';
// Load the DB class
$CI->db =& DB($params, $active_record);
}
The file you mention is just where the call happened when the issue happened.
The real issue is either:
Your settings in application/configuration/database.php
or
Your Database server is down, inaccessible or the credentials have changed

Singleton holding multiple ADODB connections

A legacy website is exhibiting unexpected behavior with it's database connections. The application connects to several MySQL databases on the same server and the original developer created a "singleton" class that holds connection objects for each of them.
Lately we have been encountering a strange behavior with the class: when a connection to www is created after creating extra, getting the instance of extra returns a connection that has the correct parameters when viewed with var_dump() but is actually connected to the www database.
What could cause this? The code has worked before at some stage. Creating a new connection on each call to getInstance() fixes the problem but I'd like to solve this the right way if possible.
<?php
class DBConnection
{
private static $default;
private static $extra;
private static $intra;
private static $www;
public static function getInstance($dbname = "default")
{
global $db; // This is an array containing database connection parameters
if(!($dbname == "default" || $dbname == "extra" || $dbname == "www" || $dbname == "intra"))
{
$dbname = "default";
}
if (empty(self::$$dbname)) // Making this pass every time fixes the problem
{
try
{
self::$$dbname = ADONewConnection('mysqlt');
if(isset($db[$dbname]))
{
self::$$dbname->connect(DBHOSTNAME, $db[$dbname]["dbusername"], $db[$dbname]["dbpassword"], $db[$dbname]["dbname"]);
}
else
{
// fallback
self::$$dbname->connect(DBHOSTNAME, DBUSERNAME, DBPASSWORD, DBNAME);
}
self::$$dbname->SetFetchMode(ADODB_FETCH_ASSOC);
self::$$dbname->execute("SET NAMES utf8");
return self::$$dbname;
}
catch(Exception $e)
{
exit("DB connection failed");
}
}
else
{
return self::$$dbname;
}
}
}
Here's a simplified example of the class misbehaving:
$cn = DBConnection::getInstance("extra");
$cn->debug = true;
$rs = $cn->execute("SELECT * FROM messages WHERE id = ".$this->id);
The last line fails with the error message "Table www.messages does not exist".
1: You don't need to establish connection in getInstance().
getInstance must not do anything, but return instance of DB class.
2: when you do self::$$dbname->connect(, if (empty(self::$$dbname)) will return you false next time you call it.
Singleton is described here: http://en.wikipedia.org/wiki/Singleton_pattern
What you have - it's just a static method.

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

PHP Session + MySQL resource

Is it possible to give a mysql resource to a $_SESSION variable ?
//mysqldb.inc.php
class mySqlDb
{
private $link;
public function __construct($_host = '', $_db = '', $_user = '', $_pwd = '')
{
$link = mysql_pconnect(...);
}
public function query($data)
{
$r = mysql_query($data, $this->link);
return $r;
}
}
//index.php
session_start();
include_once('mysqldb.inc.php');
$sqlobj = new mySqlDb();
$sqlobj->dbconnect($db_host, $db_name, $db_user, $db_pwd);
$_SESSION['mysqldb'] = $sqlobj;
//check.php
session_start();
include_once('mysqldb.inc.php');
$sqlobj = $_SESSION['mysqldb'];
$sqlobj->query(...);
$sqlobj->query(...) return
Fatal error: main(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "mySqlDb" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition in D:\apache\www\check.php on line 4`
If I use $_SESSION['mysqldb'] = serialize($sqlobj) and $sqlobj = unserialize($_SESSION['mysqldb']) I have this error:
Warning: mysql_query() expects parameter 2 to be resource, integer given in D:\apache\www\mysqldb.inc.php on line ...
You cannot persist php resources.
That's it - you just cannot. So you need to connect to database each time.
The $_SESSION documentation notes:
Because session data is serialized, resource variables cannot be stored in the session.
You have this:
$sqlobj = new mySqlDb();
But then you do this:
$_SESSION['mysqldb'] = $sql;
I.e. you're setting $_SESSION['mysqldb'] to an object that doesn't exist. Try $sqlobj instead.

Categories