Jump to content

PHP Class for DB Connect


Recommended Posts

I'm trying to condense all of my connection functions down into one class, to make the whole process easier. Instead having to remember the names of 4 functions; I just have to remember one class and the attributes used in the class.

 

I'm running in to a problem though.

 

/*Connect to DB*/
$LoginDB = new DBConnection('mysqli', 'persist', 'db418598519');

/*Encode - Sanitize user input for query*/
$sanitized_email = MySQLi_sanitize($LoginDB, $login_username);

 

This code is generating: Fatal error: Call to undefined method DBConnection::real_escape_string()

 

The class:

class DBConnection{

public function __construct($mysqlipdo, $persistcoe, $dbname, $user = "username"){

	if($mysqlipdo=="pdo" && $persistcoe=="persist"){
	$DBconnect = new SafePDO_errordisplay("mysql:host=db.1and1.com;dbname=$dbname", $user, "pass", array(PDO::ATTR_PERSISTENT => true));
	}
	elseif($mysqlipdo=="pdo" && $persistcoe=="coe"){
	$DBconnect = new SafePDO_errordisplay("mysql:host=db.1and1.com;dbname=$dbname", $user, "pass");
	}
	elseif($mysqlipdo=="mysqli" && $persistcoe=="persist"){
	$DBconnect = new mysqli_errordisplay('p:db.1and1.com', $user, "pass", $dbname);
	}
	elseif($mysqlipdo=="mysqli" && $persistcoe=="coe"){
	$DBconnect = new mysqli_errordisplay('db.1and1.com', $user, "pass", $dbname);
	}
	else{
	}
return $DBconnect;
}
}

 

function

/*Sanitize user input for MySQLi connections*/
function mysqli_sanitize($conn,$formValue){
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {	
$formValue = stripslashes($formValue);
}
$formValue = $conn->real_escape_string($formValue);
return $formValue;
}

Link to comment
Share on other sites

Alright, I changed it to this:

 

class DBConnection{

public function __construct($mysqlipdo, $persistcoe, $dbname, $user = 'dbo418598519'){

	if($mysqlipdo=="pdo" && $persistcoe=="persist"){
	$this->DBconnect = new SafePDO_errordisplay("mysql:host=db.1and1.com;dbname=$dbname", $user, "pass", array(PDO::ATTR_PERSISTENT => true));
	}
	elseif($mysqlipdo=="pdo" && $persistcoe=="coe"){
	$this->DBconnect = new SafePDO_errordisplay("mysql:host=db.1and1.com;dbname=$dbname", $user, "pass");
	}
	elseif($mysqlipdo=="mysqli" && $persistcoe=="persist"){
	$this->DBconnect = new mysqli_errordisplay('p:db.1and1.com', $user, "pass", $dbname);
	}
	elseif($mysqlipdo=="mysqli" && $persistcoe=="coe"){
	$this->DBconnect = new mysqli_errordisplay('db.1and1.com', $user, "pass", $dbname);
	}
	else{
	}
}

public function connect(){
return $this->DBconnect;
}
}

 

$LoginDB = new DBConnection('mysqli', 'persist', 'db418598519');
$LoginDB->connect();

 

Still same problem.

 

And I'm not using the real_escape_string with pdo. I'm calling a MySQL persistent connection through the DBConnection class.

Link to comment
Share on other sites

I'm also looking to convert the mysqli_sanitize to a class as well:

 

class mysqli_escape extends DBConnection{
	public function mysqli_sanitize($formValue){
		if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {	
		$this->formValue = stripslashes($formValue);
		}
	$formValue = $this->real_escape_string($formValue);
	return $this->formValue;
	}
}

 

With that, the error is now:

Fatal error: Call to undefined method DBConnection::MySQLi_sanitize()

 

/*Connect to DB*/
$LoginDB = new DBConnection('mysqli', 'persist', 'db418598519');
$LoginDB->connect();

/*Encode - Sanitize user input for query*/
$sanitized_email = $LoginDB->mysqli_sanitize($login_username);

Link to comment
Share on other sites

Now I'm getting:

 

Fatal error: Call to undefined method DBConnection::query()

 

/*Connect to DB*/
$LoginDB = new DBConnection;
$LoginDB->connect('mysqli', 'persist', 'db418598519');

/*Encode - Sanitize user input for query*/
$sanitized_email = $LoginDB->mysqli_sanitize($login_username);
$encoded_password = md5s($login_password);

/*run query*/
$result = $LoginDB->query("SELECT * FROM user WHERE email_address='$sanitized_email' AND password='$encoded_password'");
$num_rows = $result->num_rows;
$rows = $result->fetch_assoc();

 

class DBConnection {
    private $DBconnect;

    public function connect($mysqlipdo, $persistcoe, $dbname, $user = 'dbo418598519'){
        
        if($mysqlipdo=="pdo" && $persistcoe=="persist"){
        $this->DBconnect = new SafePDO_errordisplay("mysql:host=db.1and1.com;dbname=$dbname", $user, "pass", array(PDO::ATTR_PERSISTENT => true));
        }
        elseif($mysqlipdo=="pdo" && $persistcoe=="coe"){
        $this->DBconnect = new SafePDO_errordisplay("mysql:host=db.1and1.com;dbname=$dbname", $user, "pass");
        }
        elseif($mysqlipdo=="mysqli" && $persistcoe=="persist"){
        $this->DBconnect = new mysqli_errordisplay('p:db.1and1.com', $user, "pass", $dbname);
        }
        elseif($mysqlipdo=="mysqli" && $persistcoe=="coe"){
        $this->DBconnect = new mysqli_errordisplay('db.1and1.com', $user, "pass", $dbname);
        }
        else{
        }
    return $this->DBconnect;
    }

    public function mysqli_sanitize($formValue){
        if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {    
            $this->formValue = stripslashes($formValue);
        }
     $formValue = $this->DBconnect->real_escape_string($formValue);
        return $this->formValue;
    }
}  

Link to comment
Share on other sites

The error is pretty self-explanatory.  Your DBConnection class doesn't have a query() method.  You need to write one.

 

So I'm basically going to have to recreate every single method used by MySQLi? Cause that's where this is headed.

 

At that point screw OOP.

 

I thought once I established a connection I'd be able to use the built in functions of php.

 

A query method would essentially be this correct:

 

public function query($query){
return $this-DBconnect->query($query);
}

 

 

Would there some how be a way to tie in the mysqli connection class into the DBConnection class? Or would that not solve the issue here?

 

/*Include errors for mysqli connections*/
class mysqli_errordisplay extends mysqli {
    public function __construct($host, $user, $pass, $db) {
        parent::__construct($host, $user, $pass, $db);

        if (mysqli_connect_error()) {
            die('Connect Error (' . mysqli_connect_errno() . ') '
                    . mysqli_connect_error());
        }
    }
}

Link to comment
Share on other sites

The error is pretty self-explanatory.  Your DBConnection class doesn't have a query() method.  You need to write one.

 

So I'm basically going to have to recreate every single method used by MySQLi? Cause that's where this is headed.

 

At that point screw OOP.

 

I thought once I established a connection I'd be able to use the built in functions of php.

 

A query method would essentially be this correct:

 

public function query($query){
return $this-DBconnect->query($query);
}

 

Yes, that's what your query method should look like.

 

Listen, when you create a wrapper object (which is what you're doing, since your object merely contains an instance of a MySQLi or PDO object), in order to get at the methods associated with the internal object, you'll need to delegate, which is what that code does above.

 

That said, you don't necessarily need to create a wrapper object.  You have a mutant Factory (it's an OOP pattern) on your hands here.  Instead of selecting a particular type of DB to use and then wrapping it in a custom object, which would require you to write a delegate method for everything you want to do, just return the correct type of DB object.

 

class DBFactory {
    public static function connect($mysqlipdo, $persistcoe, $dbname, $user = 'dbo418598519') {
        if($mysqlipdo=="pdo" && $persistcoe=="persist") {
           return new SafePDO_errordisplay("mysql:host=db.1and1.com;dbname=$dbname", $user, "pass", array(PDO::ATTR_PERSISTENT => true));
        }
        elseif($mysqlipdo=="pdo" && $persistcoe=="coe") {
           return new SafePDO_errordisplay("mysql:host=db.1and1.com;dbname=$dbname", $user, "pass");
        }
        elseif($mysqlipdo=="mysqli" && $persistcoe=="persist") {
           return new mysqli_errordisplay('p:db.1and1.com', $user, "pass", $dbname);
        }
        elseif($mysqlipdo=="mysqli" && $persistcoe=="coe") {
           return new mysqli_errordisplay('db.1and1.com', $user, "pass", $dbname);
        }
    }
}

// Usage

$DB = DBFactory::connect(/* args */);

 

All that said, I strongly urge you to stop where you're at and get a good resource on OOP in PHP (I'm partial to PHP Objects, Patterns, and Practice).  You're writing very convoluted code with your _errordisplay variants, the kind of thing that will inevitably create headaches and heartbreak down the road. 

Link to comment
Share on other sites

Edit: essentially states what KevinM1 posted above ...

 

You are not using your code the way you intended, based on how you have written the ->connect() method.

 

Your ->connect() method RETURNS an instance of the underlying database class (mysqli or pdo.) You need to assign that to a variable (you are not currently using the returned value at all) and then use that variable to reference the methods of the underlying database class.

 

$LoginDB = new DBConnection;
$DB = $LoginDB->connect('mysqli', 'persist', 'db418598519'); // $DB is an instance of the underlying database class 

...

$result = $DB->query("SELECT * FROM user WHERE email_address='$sanitized_email' AND password='$encoded_password'");

Link to comment
Share on other sites

OOP is notoriously difficult to learn, and really shouldn't be used for production apps until:

 

1. You know what you're doing

2. You know why you're doing it

 

OOP isn't just about slapping code in objects and calling it a day.  It's about knowing when/where/why/how to use classes and objects to make clean, modular, reusable code.  If you're not at that level, then don't force it in a full blown app.  There's nothing wrong with procedural programming, and if that's what you're comfortable with, use it.  Learn OOP on the side.

Link to comment
Share on other sites

OOP is notoriously difficult to learn, and really shouldn't be used for production apps until:

 

1. You know what you're doing

2. You know why you're doing it

 

OOP isn't just about slapping code in objects and calling it a day.  It's about knowing when/where/why/how to use classes and objects to make clean, modular, reusable code.  If you're not at that level, then don't force it in a full blown app.  There's nothing wrong with procedural programming, and if that's what you're comfortable with, use it.  Learn OOP on the side.

 

It's actually not a live site. And I figured out the issue (a session expired that I manually set myself, pretty much not related what I'm trying to do here), everything's all good now. Plus I got this working somewhat.

 

The below connects without an issue, its just now giving me an error of:

Fatal error: Call to undefined method mysqli_errordisplay::mysqli_sanitize()

So it's seeing it as the errordisplay class; which I guess is a good thing for the connection, but not the sanitize function.

 

/*Connect to DB*/
$DBConnect = new DBConnection;
$LoginDB = $DBConnect->connect('mysqli', 'persist', 'db418598519');

/*Encode - Sanitize user input for query*/
$sanitized_email = $LoginDB->mysqli_sanitize($login_username);

 

class DBConnection {
    private $DBconnect;

    public function connect($mysqlipdo, $persistcoe, $dbname, $user = 'dbo418598519'){
        
        if($mysqlipdo=="pdo" && $persistcoe=="persist"){
        $this->DBconnect = new SafePDO_errordisplay("mysql:host=db.1and1.com;dbname=$dbname", $user, "pass", array(PDO::ATTR_PERSISTENT => true));
        }
        elseif($mysqlipdo=="pdo" && $persistcoe=="coe"){
        $this->DBconnect = new SafePDO_errordisplay("mysql:host=db.1and1.com;dbname=$dbname", $user, "pass");
        }
        elseif($mysqlipdo=="mysqli" && $persistcoe=="persist"){
        $this->DBconnect = new mysqli_errordisplay('p:db418598519.db.1and1.com', $user, "pass", $dbname);
        }
        elseif($mysqlipdo=="mysqli" && $persistcoe=="coe"){
        $this->DBconnect = new mysqli_errordisplay('db.1and1.com', $user, "pass", $dbname);
        }
        else{
        }
    return $this->DBconnect;
    }

    public function mysqli_sanitize($formValue){
        if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {    
            $this->formValue = stripslashes($formValue);
        }
     $formValue = $this->real_escape_string($formValue);
        return $this->formValue;
    }
}  

 

I tried $DBConnect->mysql_sanitize and that didn't work.

Also tried $this->DBConnection->real_escape_string in the function.

Link to comment
Share on other sites

I have a work around, but it's not OO though.

 

Just running a function like this works without issue:

function mysqli_sanitize($conn,$formValue){
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {	
$formValue = stripslashes($formValue);
}
$formValue = $conn->real_escape_string($formValue);
return $formValue;
}

 

$DB = new DBConnection;
$LoginDB = $DB->connect('mysqli', 'persist', 'db418598519');

/*Encode - Sanitize user input for query*/
$sanitized_email = mysqli_sanitize($LoginDB, $login_username);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.