Solved

PHP Class

Posted on 2013-10-30
16
1,009 Views
Last Modified: 2013-10-31
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
Comment
Question by:deltadoc
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
  • 4
  • +2
16 Comments
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39612315
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
 

Author Comment

by:deltadoc
ID: 39612341
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
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39612348
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
Technology Partners: 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!

 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39612358
Within a class you can't use die(): you have to throw an exception using try...catch block: http://us3.php.net/exceptions
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39612360
But the rest should work...
0
 

Author Comment

by:deltadoc
ID: 39612416
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
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39612481
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
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39612524
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
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39612554
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
 

Author Comment

by:deltadoc
ID: 39612640
ok so how would you configure this
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39612666
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
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39612862
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
 

Expert Comment

by:akuss
ID: 39614036
Ok i got this now everything is working i have one more question though in terms of security this is ok to use?
0
 

Author Comment

by:deltadoc
ID: 39614086
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
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39614092
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
 

Author Comment

by:deltadoc
ID: 39614170
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

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

696 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question