Jump to content

[SOLVED] Need help `encapsulating` database connection resource


Recommended Posts

<?php

require_once "constants/dbInfo.const.php";

class db
{

private        $conn;
private static $instance;

 private function __CONSTRUCT()
 {
  
 	$conn = mysql_connect( HOST, USER, PASS ) or trigger_error( 'Couldn\'t connect to mysql', E_USER_ERROR );
 	$db   = mysql_select_db( DB, $conn )or trigger_error( 'Couldn\'t select requested database', E_USER_ERROR );
  
 		$this->conn = $conn;

 }

 	static function instance()
 	{
 		if ( !isSet( self::$instance ) )
 			self::$instance = new self();

 		return self::$instance;

        }

 		public function cleanStr( $str, $args )
 		{
 			if ( !is_array($args) || empty($args) )
 				return false;

 				forEach( $args AS $k => $v )
 				{

 					if ( is_string( $v ) )
 					{
 					 
 						if ( substr( $v, 0, 6 ) == 'clean:' )
 						$args[$k] = mysql_real_escape_string( substr( $v, 6 ), $this->conn );
 					}
 				}

 				return vsprintf( $str, $args );
 		}

 			public function query( $str )
 			{
 				 
 				return mysql_query( $str, $this->conn );

 			}

 				public function arr( $result, $type = MYSQL_NUM )
 				{

 					return mysql_fetch_array( $result, $type );

 				}

 				public function obj( $result )
 				{

 					return mysql_fetch_object( $result );

 				}

}

?>

 

I have made the above class in an attempt to learn about OOP in PHP, I would like to (and intended to) make it so that the link to the database could only be accessed via the classes methods. 

 

However, when I run the following piece of code I can call mysql_query etc... without having to go through the classes methods.

 

<?php
error_reporting(E_ALL);
require_once "../class/connections/dataBase.inc.php";

db::instance();

$query = "SELECT user FROM users WHERE id = 1 LIMIT 1";
$result= mysql_query($query)or trigger_error(mysql_error());
$row   = mysql_fetch_row($result);

echo $row[0] . "<br >\n";

$arr[] = 'clean:Andy';
$arr[] = 1;

$query  = db::instance()->cleanStr( "SELECT user FROM users WHERE user = '%s' AND id = %d ", $arr );
$result = db::instance()->query( $query );
$row    = db::instance()->obj( $result );

echo $row->user;

?>

 

This outputs 

Andy<br >
Andy

 

 

Is there any way I can make the connection only accessible via the class?

 

Thanks.

It all comes down to the optional link_identifier parameter for mysql_query() et al.

If no value is specified for the parameter, then the value will default to the last link opened by a mysql_connect.

 

If you really need to suppress this behaviour, you could try opening and then closing a second link within your db::instance() method (without saving it in $db->conn). This would then become the default for the link_identifier parameter for mysql_query(), but as it has since been closed it would result in an error when trying to use mysql_query().

Note that your own queries being issued through the db class would need to specify the $db->conn value as the link_identifier parameter.

I'm not sure if Mark is on the right track, but the problem is that once a connection is open, mysql_query is finds it with or without the link,

 

so any mysql_query after db::instance(); will work,

 

I guess opening the connection on use and then closing the connection after would work! but isn't ideal!

Ahh ok, thanks. Ill just leave the link open and edit my cleanStr() method lol.

 

I assumed I wouldnt be able to call mysql_real_escape_string outside of the class, wont be needing it now anyhow lol

 

Thanks for the help :)

Okay i was just thinking about the logic, the mysql_query will use the last "active" connection, if link is not set..

 

Soooo... maybe add

mysql_connect();

right after

$this->conn = $conn;

this will be used any anything that doesn't use the link and will fail as theirs no database selected..

its worth a try

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.