Detect if mysql or mysqli is being called for connection - php

is there a way to check which type of mysql connection is being called mysql or mysqli. what I want to do is have a If statement to call mysql or mysqli connection until I can change out all my coding.
this is my current connection file. would just duplicating what's below but with mysqli accomplish what i'm trying to do?
$dbc = mysql_connect ($db_server, $db_user, $db_pass);
mysql_select_db ($db_name) or die(mysql_error());
$g_link = false;
function GetDbConn()
{
global $g_link;
if( $g_link )
return $g_link;
$g_link = mysql_connect( 'localhost', 'username', 'password') or die('Could not connect to server.' );
mysql_select_db('social_db', $g_link) or die('Could not select database.');
return $g_link;
}
function CleanUpDB()
{
global $g_link;
if( $g_link != false )
mysql_close($g_link);
$g_link = false;
}

You can use get_resource_type function:
if(is_resource($g_link) && get_resource_type($g_link)=='mysql link'){
echo 'MYSQL';
}else{
if(is_object($g_link) && get_class($g_link)=='mysqli'){
echo 'MYSQLI';
}
}
Also, it's better to save connection type when you want to create connection and then use it.

There is absolutely no point in checking which type of mysql connection is being called mysql or mysqli.
While changing "all your coding", you have to make use of some sort of db access library, which will be obviously using a new driver as it's underlying level. And as this library obviously have to be written using new api, no verifications ever needed.
While just rewriting old api calls to the new api calls will make no sense.

Related

How to get mysqli instance recognised in functions?

I'm in the process of upgrading from mysql to mysqli.
All my mysql code was procedural, and I'd now like to convert to OOP, as most mysqli examples online are in OOP.
The problem I'm having is that, with mysql, once I had set up a connection, I never had to inject that connection into any functions as arguments for mysql to be accessible in the function.
Here is my old connection code:
$location = "localhost";
$user = "rogerRamjet";
$pass = "bestPassInTheWorld";
$dbName = "myDBName";
$link = mysql_connect($location, $user, $pass);
if (!$link) {
die("Could not connect to the database.");
}
mysql_select_db("$dbName") or die ("no database");
And an example function that has access to the mysql connection, without $link needing to be injected into the function:
function getUser($data)
{
$data=mysql_real_escape_string($data);
$error = array('status'=>false,'userID'=>-1);
$query = "SELECT `user_id`, `user_email` FROM `myTable` WHERE `data`='$data'";
if ($result = mysql_query($query))
{
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ($row['user_id']!="")
{
return array( 'status'=>true, 'userID'=>$row['user_id'], 'email'=>$row['user_email'] );
}
else return $error;
}
else return $error;
}
And here's my new mysqli connection:
$mysqli=new MySQLi($location, $user, $pass, $dbName);
So, to upgrade the first line in the above function, I'd need:
$data = $mysqli->real_escape_string($data);
But that throws the error:
Undefined variable: mysqli
Does this mean that for any function needing access to $mysqli, I need to inject $mysqli as an argument into it, or is there a way for it to be accessible the way mysql is without injection?
I know I need to move to prepared statements, but this is just so I can get my head around mysqli basics.
Making the variable global is bad practice. The singleton pattern solves the issue of needing to share one instance of an object throughout an application lifecycle. Consider using a Singleton.
The crude solution would be global $mysqli; as first line of your function. But as hsan wrote, read about PHP variable scope

How do I make $con available as a parameter of $Query?

I can get by with editing procedural PHP (just), but OOP is a different thing. So I'm not that experienced with what I'm doing here, but I'm trying my best...
I have a file called Quote.object.php containing the following:
$Query = new DbQuery( "INSERT", "quotes", $array );
$this->id = mysqli_insert_id();
mysqli_insert_id needs to be fed a DB connection parameter, but I'm not sure how to do it. There is another file called Mysql.handler.php containing the database connection variable - is there a way that I can make $con available as a parameter of $Query above?
class DbQuery extends DbConnectionInfo{
// file: includes/classes/MysqlQuery.php
// contains functions needed to perform queries on mysql database and functions for necessary data processing for application
// SELECT = new DbQuery("select", table,cols[$value] ,where[$col=$value],order[$value],limit);
// INSERT = new DbQuery("insert", table, data[$col=$value]);
// UPDATE = new DbQuery("update", table, data[$col=$value],where[$col=$value],limit);
// set testing as true for SQL reports in page
var $results;
var $sql;
function __construct($mode,$table = '',$var1 = '',$var2 = '',$var3 = '',$var4='')
//connects to database according to info in DbConnectInfo, runs query, closes connection
{
$temp = '';
$con = mysqli_connect($this->host, $this->user, $this->pass) or die ('There was a problem connecting to the database ' . (ENVIRONMENT == 'Development' ? mysqli_error() . "$this->user, $this->pass, $this->host" : ''));
mysqli_select_db($con,$this->db) or die ('There was a problem connecting to the database' . (ENVIRONMENT == 'Development' ? mysqli_error() : ''));
I'm trying to get $con from DbQuery so I can put it into mysqli_insert_id(). I assume that's what I need? Is there a way to get $con from DbQuery and put into mysqli_insert_id()? Or do you need more information to know this?
NB I've tried to be concise in trying to show just relevant information, apologies if I've missed other helpful info.
You're defining an object, so make $con a class variable, e.g.
function __construct() {
$this->con = mysqli_connect(...);
^^^^^^^----store in object
}
function foo() {
$result = mysqli_query($sql, $this->con);
^^^^^^^^---retrieve from object
}

Get a database connection error in a class

I didn't realize there was an OO way to use mysqli, so I built a class called DB. During __construct it takes the hostname, username, password, and database name. Given the following code:
$myDB = new DB("localhost", "user", "password", "database");
$myDBConnect = $myDB->connect();
if(!$myDBConnect) {
echo "<strong>The following error has occurred: " . $myDB->getError();
}
The variable obviously contains FALSE because this if statement is currently returning TRUE. Here is the method from the DB class:
public function connect() {
// Create connection
$this->dbConnx = mysqli_connect($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if(mysqli_connect_errno($this->dbConnx)) {
$this->dbError = mysqli_error($this->dbConnx);
return false;
}
}
I'm not getting any error detail. I tried adding or die(mysqli_error()); in the connect method, but it always just outputs the text from the file that $myDB is instantiated in. I also tried variations on the error reporting code, including having no argument in mysqli_connect_errno() and using $this->dbError = mysqli_connect_error() with and without the connection argument.
Is this needlessly complicating the OO way to use mysqli? or am I missing something simple that will allow me to move on using the code I've already got?
Thanks in advance for your time.
if is not variable
if(!$myDBConnect) {
^--remove variable sign here
EDIT:
your connection should be
$myDB = new mysqli("localhost", "user", "password", "database");
Maybe you forgot the return true statement in the "connect" method?
Also you should use PDO.
Your connect() function is returning false on failure and nothing on success, so it will always fail the if. Try adding return true; at the end of that function.

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.

PHP Database Class and new() Function

I have, what I think/hope, is a very simple PHP question. I have made a class to create database connections and issue common queries. I am trying to open two different database connections by creating two objects from the same database class. My code is as follows:
//connect to DB
$dbh = new DB('localhost', 'db1', 'user', 'pass');
//check connection
if(!$dbh->getStatus()) {
echo($dbh->getErrorMsg());
die;
}//if
//connect to DB 2
$dbh2 = new DB('localhost', 'db2', 'user', 'pass');
//check connection
if(!$dbh2->getStatus()) {
echo($dbh2->getErrorMsg());
die;
}//if
However, when I call a method for $dbh to query the database, it attempts to query with the credentials for $dbh2.
My DB constructor is below:
class DB {
function __construct($host, $db, $user, $pass) {
$dbh = mysql_connect($host, $user, $pass);
mysql_select_db($db, $dbh);
if(!$dbh) {
$this->status = false;
$this->error_msg = 'Error connecting to database: '.mysql_error();
return(false);
}//if
$this->dbh = $dbh;
$this->resetStatusAndErrors();
return($dbh);
}//_construct
Simple solution: Use PDO instead. It does exactly what you want, probably has better syntax and implementation and abstracts the interface for DB access.
You're not showing the full class, but the most probable reason is that you are not passing the current connection to the mysql_query() command.
Save $dbh as a property of your class, and add the connection parameter to each mysql_ function that accepts it:
mysql_query("SELECT * from.......", $this->dbh);
That said, if you are building this from scratch at the moment, take a look whether you don't want to use PDO instead. It is better, safer and more flexible than the old style mySQL library.
If you are using the mysql extension (using either mysqli or PDO_MySQL would give both superior performance, more features, etc., so check that for new code), you'll have to store the database handle, and use that on every mysql_* call:
class db {
....
function query($query){
return mysql_query($query, $this->dbh);//notice the second parameter.
}
}

Categories