• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1031
  • Last Modified:

PHP Class

Hello im redeveloping our client login from asp code to php to extend its life and i'm trying to put my database connection into a class and its not working see below for what i have when i use

<?php include_once('classes/mssqlconnect.class.php')

This file includeds the following

<?php

class msSQLConnect {

	public function dbConnMSSQL() {

		$serverName = "DELTALITHIUM\LITHIUMSQL";
		$connectionInfo = array( "Database"=>"", "UID"=>"", "PWD"=>"");
		
		// Connect to MSSQL
		$conn = sqlsrv_connect( $serverName, $connectionInfo);
		
		if( $conn === false ) {
			die( print_r( sqlsrv_errors(), true));
		}
	}
}
// Instantiate the Connect class
$mssqlconnect = new msSQLConnect();

Open in new window



However its keeps erroring the rest of the code that is working is as follows can someone explain what i'm doing wrong

			//include_once('classes/mssqlconnect.class.php');
			$serverName = "";
			$connectionInfo = array( "Database"=>"", "UID"=>"", "PWD"=>"");
			
			// Connect to MSSQL
			$conn = sqlsrv_connect( $serverName, $connectionInfo);
			
			if( $conn === false ) {
				die( print_r( sqlsrv_errors(), true));
			}			
		
			$sql = 'SELECT * FROM tbldoc_net';
			
			$stmt = sqlsrv_query( $mssqlconnect, $sql);
			if( $stmt === false ) {
				die( print_r( sqlsrv_errors(), true));
			}
			while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
				echo $row['Doc_Filename'].", ".$row['Doc_Entered_by']."<br />";
			}
			
			sqlsrv_free_stmt( $stmt);
			sqlsrv_close($mssqlconnect);

Open in new window

0
deltadoc
Asked:
deltadoc
  • 5
  • 4
  • 4
  • +2
1 Solution
 
Marco GasiFreelancerCommented:
You should do one of the following:

1
$mssqlconnect = new msSQLConnect();
$mssqlconnect->dbConnMSSQL();

2
call dbConnMSSQL() function in the constructor of the class:

<?php

class msSQLConnect {

      public function dbConnMSSQL() {

            $serverName = "DELTALITHIUM\LITHIUMSQL";
            $connectionInfo = array( "Database"=>"", "UID"=>"", "PWD"=>"");
            
            // Connect to MSSQL
            $conn = sqlsrv_connect( $serverName, $connectionInfo);
            
            if( $conn === false ) {
                  die( print_r( sqlsrv_errors(), true));
            }
      }

       public function__construct(){
          $this->->dbConnMSSQL();
       }
}
// Instantiate the Connect class
$mssqlconnect = new msSQLConnect();
0
 
deltadocIT ManagerAuthor Commented:
So something like this

			include_once('classes/mssqlconnect.class.php');
		
			$sql = 'SELECT * FROM tbldoc_net';
			
			$stmt = sqlsrv_query( $dbConnMSSQL, $sql);
			if( $stmt === false ) {
				die( print_r( sqlsrv_errors(), true));
			}
			while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
				echo $row['Doc_Filename'].", ".$row['Doc_Entered_by']."<br />";
			}
			
			sqlsrv_free_stmt( $stmt);
			sqlsrv_close($dbConnMSSQL);

Open in new window


Code in mssqlconnect.class.php'

class msSQLConnect {

      public function dbConnMSSQL() {

            $serverName = "";
            $connectionInfo = array( "Database"=>"", "UID"=>"", "PWD"=>"");

            // Connect to MSSQL
            $conn = sqlsrv_connect( $serverName, $connectionInfo);

            if( $conn === false ) {
                  die( print_r( sqlsrv_errors(), true));
            }
      }

      public function__construct(){
            $this->->dbConnMSSQL();
      }
}
// Initiate the Connect class
$mssqlconnect = new msSQLConnect();
0
 
Marco GasiFreelancerCommented:
You can start here to learn about OOP in Php: http://php.net/manual/en/language.oop5.php

You could do something better adding a few of variables:

<?php

class msSQLConnect {

        private $serverName;
        private $database;
        private $uid;
        private $pwd;

	public function dbConnMSSQL() {

		$serverName = $serverName;
		$connectionInfo = array( "Database"=>$database, "UID"=>$uid, "PWD"=>$pwd);
		
		// Connect to MSSQL
		$conn = sqlsrv_connect( $serverName, $connectionInfo);
		
		if( $conn === false ) {
			die( print_r( sqlsrv_errors(), true));
		}
   	}

       public function__construct($srvrName, $db, $username, $password){
            $this->serverName = $srvrName;
            $this->database = $db;
            $this->uid = $username;
            $this->pwd = $password;
            $this->->dbConnMSSQL();
       }
}
// Instantiate the Connect class
$mssqlconnect = new msSQLConnect(SERVERNAME, DB, UID, PWD);

Open in new window

                                 

Please, note the use of constant when you instantiate the class: without enter in a too complex discussion about security, it's better to use constant to pass sensitive data in your application.

Cheers
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Marco GasiFreelancerCommented:
Within a class you can't use die(): you have to throw an exception using try...catch block: http://us3.php.net/exceptions
0
 
Marco GasiFreelancerCommented:
But the rest should work...
0
 
deltadocIT ManagerAuthor Commented:
I guess im just not getting this but here is what i have not working

code from class

class msSQLConnect {

	private $serverName;
	private $database;
	private $uid;
	private $pwd;

	public function dbConnMSSQL() {

		$serverName = $serverName;
		$connectionInfo = array( "Database"=>$database, "UID"=>$uid, "PWD"=>$pwd);
		
		// Connect to MSSQL
		$conn = sqlsrv_connect( $serverName, $connectionInfo);
		
		if( $conn === false ) {
			//die( print_r( sqlsrv_errors(), true));
		}
   	}

	public function construct ($srvrName, $db, $username, $password) {
            $this->serverName = $srvrName;
            $this->database = $db;
            $this->uid = $username;
            $this->pwd = $password;
            $this->dbConnMSSQL();
       }
}
// Instantiate the Connect class
$mssqlconnect = new msSQLConnect(SERVERNAME, DB, UID, PWD); 

Open in new window


Code From Page

			include_once('classes/mssqlconnect.class.php');
			
			construct('','','','');
		
			$sql = 'SELECT * FROM tbldoc_net';
			
			$stmt = sqlsrv_query( $mssqlconnect, $sql);
			if( $stmt === false ) {
				die( print_r( sqlsrv_errors(), true));
			}
			while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
				echo $row['Doc_Filename'].", ".$row['Doc_Entered_by']."<br />";
			}
			
			sqlsrv_free_stmt( $stmt);
			sqlsrv_close($mssqlconnect);

Open in new window

0
 
Ray PaseurCommented:
Can you please give us a bitter clue than "not working" ?  Does it issue any messages, for example?  How do you detect that it is not working?
0
 
Chris StanyonCommented:
You have a number of things wrong - both in the coding and in the understanding.

The construct method in your class has to be called __construct (note the double underscore). You don't then call the construct method manually - it's called automatically when you instantiate the object. The arguments for the __construct method are the arguments you need to pass to the class name when you instantiate. Your constructor will look like this:

class myClass {

   function __construct ($srvrName, $db, $username, $password) {
      ... 
   }

}

Open in new window

Then in code you instantiate an object like this:

$someVariable = new myClass('servername', 'db', 'user', 'pass');

You will then have an object assigned to a variable and you can call the methods like so:

$someVariable->someMethod();

You seem to be trying to instatiate the class within the class file - wrong!

Before going too far on this, ask yourself why you're doing this - why do you think you need to wrap the connection in a class. Would it not just be easier to wrap the connection details in your include file?
0
 
Ray PaseurCommented:
Personally, I put the connection details in an include file.  But if you're just experimenting with PHP object-oriented programming, you might consider using a Singleton pattern for the SQ connection.  It would be something similar to this.

<?php // RAY_database_singleton.php
error_reporting(E_ALL);


// SINGLETON DATA BASE CONNECTION CLASS
class Database
{
    // CLASS PROPERTIES ARE ALL PRIVATE
    private static $connection;
    private static $instance;

    // CONNECTION VALUES
    const DB_HOST = 'localhost';
    const DB_USER = 'X';
    const DB_PASS = 'X';
    const DB_NAME = 'X';

    // NULLIFY THE CLONE
    final private function __clone() {}

    // OUR ONLY PUBLIC METHOD RETURNS THE CONNECTION
    public static function getConnection()
    {
        if (!self::$instance) self::$instance = new self();
        return self::$connection;
    }

    // CONSTRUCTOR CREATES THE CONNECTION
    private function __construct()
    {
        self::$connection
        = new mysqli
        ( self::DB_HOST
        , self::DB_USER
        , self::DB_PASS
        , self::DB_NAME
        )
        ;
        if (self::$connection->connect_error)
        {
            trigger_error(self::$connection->connect_error, E_USER_ERROR);
        }
    }
}

$mysql1 = database::getConnection();
$mysql2 = database::getConnection();


// PROVE THAT THESE ARE THE SAME OBJECT http://php.net/manual/en/language.oop5.object-comparison.php
if ($mysql1 === $mysql2) echo 'EQUAL';

// SHOW THE OBJECT
var_dump($mysql1);

Open in new window

0
 
deltadocIT ManagerAuthor Commented:
ok so how would you configure this
0
 
Chris StanyonCommented:
If you really want to wrap your connection in a class, then include the class in your document. And then call the getConnection() method, assigning the output to a varibale. You then use the variable as the connection in the normal way:

include(''database.class.php');
$conn = database::getConnection();

$sql = 'SELECT * FROM tbldoc_net';
			
$stmt = sqlsrv_query($conn, $sql);
//carry on dealing with your query here

Open in new window

0
 
Ray PaseurCommented:
I'm going to assume that you've read the PHP introductory tutorial and the pages linked here:
 http://php.net/manual/en/language.oop5.php

Put your credentials near line 27 and run this.  Please show us any error messages.

<?php // RAY_database_singleton.php
error_reporting(E_ALL);

// SEE http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/Q_28281373.html

// SINGLETON DATA BASE CONNECTION CLASS
class Database
{
    // CLASS PROPERTIES ARE ALL PRIVATE
    private static $conn;
    private static $instance;

    // NULLIFY THE CLONE
    final private function __clone() {}

    // OUR ONLY PUBLIC METHOD RETURNS THE CONNECTION
    public static function getConnection()
    {
        if (!self::$instance) self::$instance = new self();
        return self::$conn;
    }

    // CONSTRUCTOR CREATES THE CONNECTION
    private function __construct()
    {
        // PUT YOUR CREDENTIALS HERE
        $serverName = "DELTALITHIUM\LITHIUMSQL";
        $connectionInfo = array( "Database"=>"", "UID"=>"", "PWD"=>"");
        
        // CONNECT TO MSSQL
        self::$conn = sqlsrv_connect($serverName, $connectionInfo);
        
        // IF ERROR
        if(!self::$conn)
        {
            $err = sqlsrv_errors();
            trigger_error($err, E_USER_ERROR);
        }
    }
}

$mssql = database::getConnection();
var_dump($mssql);

Open in new window

0
 
akussCommented:
Ok i got this now everything is working i have one more question though in terms of security this is ok to use?
0
 
deltadocIT ManagerAuthor Commented:
Looks like i have multiple accounts i was able to make the above work I just wanted to know since someone metioned security earlier will this be a secure way to go about this?
0
 
Ray PaseurCommented:
Security is a pretty broad-brush topic.  There is nothing in this thread of conversation that creates any unnecessary security exposure, but most such exposures are data-dependent.  When I see SELECT * followed by echo without any effort to sanitize the information from the data base before writing it to the client browser, I have to assume that you have security risks throughout the web application.  Protecting the client is kind of PHP 101.
http://php.net/manual/en/function.htmlspecialchars.php

You can learn more about PHP security here.  Just scan for "security" and follow the links.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html
0
 
deltadocIT ManagerAuthor Commented:
I dont have serious security risks im just re-developing and shortcutting alot of things for now until i have a base system to work with...

I'm one of the unfortunate IT personalities that wear quite a few hats

I appreciate the articles and appreciate the help with getting through this little problem :)
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 5
  • 4
  • 4
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now