Jump to content

OO help!


OAFC_Rob

Recommended Posts

Okay, ive been trying to get my head around OO PHP and I thought I was getting somewhere, but now I'm stuck.

 

I firstly created a database connection class, which works fine and then I wanted to create a login script, but in the process of doing that I had a brain wave to create a generalised SQL query script that basiclaly strips out all junk to help add some extra security to my site, but Ive got myself all confused now. HELP PLEASE!

 

What I thought should be happening is the following;

 

1. The user input username etc... this posted onto itself, if it is create a new object of login class and make the loginAction function variables equal that of what has been posted across.

2. Now we are in login class and within the function loginAction where we call an object of SQL Query class and then call the function called sql.

3. This should now strip out any hacks, sql injections I believe and jsut give back some clean data to be used in the sql query, correct?

4. Now back in login class if there are results we should be dying out a message to see if it has worked. But this just doesn't happen.

 

Do I have to inlcude the sql query class within the login class page?

Am I calling it all correctly?

 

Any help would be GREATLY APPRECIATED, I look forward to you replies.

 

Database connection class

<?php

class databaseConnectionClass
    {

	public $databaseHostname;
	public $databaseUsername;
	public $databasePassword;
	public $databaseName; 

        # MAIN CONNECTION TO THE DATABASE, PASSING THE 
        public function databaseConnection()
        {
           
		    $this->connectionLink = mysql_pconnect($this->databaseHostname, $this->databaseUsername, $this->databasePassword) or trigger_error(mysql_error(),E_USER_ERROR);
           
		    return $this->connectionLink;
        }

        # SELECTS THE DATABASE WE WANT
        public function databaseConnectionSelect()
        {
            $this->selectDatabase = mysql_select_db($this->databaseName, $this->connectionLink);
            
			return $this->selectDatabase;
        }

        # CALL ALL THE DATABASE CONNECTION OBJECTS
        public function databaseConnectionProcess($objDatabaseConnect)
        {
            $objDatabaseConnect->databaseConnection($objDatabaseConnect);
            $objDatabaseConnect->databaseConnectionSelect($objDatabaseConnect);
        }

        # BUILDS A OBJECT METHOD 
        public function databaseConnectionMain($objDatabaseConnect)
        {
            $objDatabaseConnect->databaseConnectionProcess($objDatabaseConnect);
        }
                
                # CLOSES THE MYSQL CONNECTION ADDED ON 04/05/2011
                public function databaseConnectionClose ($objDatabaseConnect)
                {
                    mysql_close($objDatabaseConnect);
                }

    }
?>

 

SQL Query class

<?php
    #THIS CLASS CREATES AND OBJECT, WHICHS SETS THE OBJECT TO EQUAL THE INFO FROM "dbConnectClass.php"
            require_once ("config/config.php");
            require_once ("dbConnectClass.php");

    $objDatabaseConnect = new databaseConnectionClass();
    $objDatabaseConnect->databaseHostname = $databaseHostname;
    $objDatabaseConnect->databaseUsername = $databaseUsername;
    $objDatabaseConnect->databasePassword = $databasePassword;
    $objDatabaseConnect->databaseName = $databaseName;

    $objDatabaseConnect->databaseConnectionMain($objDatabaseConnect);
            
            #A CLASS TO RUN EACH QUERY, TO HELP TO SQL INJECTIONS
            class databaseQuery
            {
                #FUNCTION TO PREVENT SQL INJECTION
                function sql($sql)
                {
                    $args = func_get_args();
                    $sql = array_shift($args);
                    $sql = str_replace("?", "%s", $sql);
                    $args = array_map('mysql_real_escape_string', $args);
                    array_unshift($args,$sql);
                    $sql = call_user_func('printf',$args);
                    $result = msql_query($sql) OR trigger_error(mysql_error($sql),E_USER_ERROR);
                    if($result)
                    {
                        return $result;
                    }
                    else
                    {
                        $error = "Error";
                        return $result;
                    }
                }
            }
?>

 

Login Class

<?php
        #DO I HAVE TO INCLUDE EACH CLASS I'M CALLING
#include("C:/xampp/htdocs/duff3/commonResources/dbConnection/dbQueryClass.php");
class login
{
            #ENCRYPT VARIABLE	
            var $encrypt = FALSE; 
            
                function loginAction ($username,$password,$active)
	{
                   if($this->$encrypt == TRUE)
                   {
                      $password = md5($password); 
                   }
                  
                   #MAKING AN OBJECT OF "dbQueryClass.php"
                   $result = new databaseQuery ();
                   $result->sql = "
                                    SELECT 
                                        userName,
                                        password,
                                        active
                                    FROM
                                        tbl_user_accounts
                                    WHERE 
                                        username = '$username'
                                    AND 
                                        password = '$password'
                                    AND 
                                        active = '$active'
                                 ";
                   #BELIEVE THAT THIS IS NOW GETTIGN RUN BY THE "sql" FUNCTION
                  # $result = mysql_query($sql) OR trigger_error(mysql_error(),E_USER_ERROR);
                   
                   if(mysql_num_rows($result) > 0)
                   {
                    die("Yes it is working");   
                   }
                   else
                   {
                    die("damn it!");
                   }
                   

	}

	function logoutAction ()
	{

	}

	function timeoutAction ()
	{

	}
}

?>

 

Finally login.php page

 

<?php
require_once("../commonResources/includes/headerArea.php");
require_once("../commonResources/includes/navigationArea.php");
        include("../commonResources/php.lib/loginClass.php");
        
        if(isset($_POST))
        {
          
           #BELIEVE THIS IS DOING: 
            #1. CREATING AN OBJECT OF THE LOGIN CLASS
            #2. SETTING THE OBJECT FUNCTION "loginAction" TO POST USERNAME
            #3. SETTING THE OBJECT FUNCTION "loginAction" TO POST PASSWORD
            $login = new login();
    $login->loginAction = $_POST["username"];
            $login->loginAction = $_POST["password"]; 
            $login->loginAction = 1; 
           
        }
?>
                    
                    <div class="paraBlock"><!--OPEN DIV FOR PARA BLOCK -->
                    
                        <form action="" method="post">
			<table>
				<tr>
					<td>
						<label>Username:</label>
					</td>
					<td>
						<input type="text" name="username" />
					</td>
				</tr>
				<tr>
					<td>
						<label>Password:</label>
					</td>
					<td>
						<input type="password" name="password" />
					</td>
				</tr>
				<tr>
					<td>
						 
					</td>
					<td>
						<input type="reset" value="Clear"/>
						<input type="submit" value="Log in"/>
					</td>
				</tr>
			</table>
		</form>
                        
                    </div><!--CLOSE DIV FOR PARA BLOCK-->
                    
<?php
require_once ("../commonResources/includes/footerArea.php");
?>              

Link to comment
Share on other sites

Wow....

 

I hate to say this, but you're way, way, way off track with all of this.  Ditch whatever resource you're using to teach yourself PHP OOP, then go to the manual (start here: http://www.php.net/manual/en/language.oop5.basic.php and continue down the list of links on the left) and start again fresh.

 

There's too much wrong here to efficiently correct in a message board setting.

Link to comment
Share on other sites

Your not way way off like this guy just said, but your off.... I haven't tested the other class's in your code but you def not utilizing your own method correctly.

 

Change this:

$login = new login();
    $login->loginAction = $_POST["username"];
            $login->loginAction = $_POST["password"]; 
            $login->loginAction = 1; 

 

To this:

 

$login = new login();
    $login->loginAction($_POST["username"],$_POST["password"],1);


 

Also your DB Connection Class is way way over kill. Your jumping all around you class when you could get everything done on a few functions.

 

Link to comment
Share on other sites

Here is an example of my DB connect class.

 


Class DBConnect{
var $user = 'username';
var $pass = 'password';
var $db = 'mydb'; 
var $server = 'localhost';

Private Function setServer($server){
$this->server = $server;
}

Function setUser($user){
$this->user = $user;    
}

Function setPass($pass){
$this->pass = $pass;
}
         
Function setDb($db){
    $this->db = $db;
}         

Function openCon(){
mysql_connect($this->server,$this->user,$this->pass);
mysql_selectdb($this->db);
}
         
  } #End Class
  ?>

 

It would be used like this.

 

$con = new DBConnect();
$con->openCon();

 

If I need to change any of the settings you can use the set Functions like this.

 

$con = new DBConnect();
$con->setServer("Host2")
$con->setUser("User2");
$con->setPass("Pass2");
$con->setDb("DB2");
$con->openCon();

 

 

Link to comment
Share on other sites

Your not way way off like this guy just said

 

1. He's using PHP 4 syntax when he really should be using PHP 5 syntax (PHP 5 has been around since 2004).

2. Like you said, he's trying to assign form values to a method rather than passing them through the method's argument list (which shows a misunderstanding of functions in general).

3. He has public members, and then is dynamically creating more public members because he doesn't understand when to use the 'this' keyword.

4. He's attempting to invoke his database methods with parameters, even though they've been defined as being parameterless (databaseConnection, databaseConnectionSelect).

5. He's not actually passing his SQL statement to his databaseQuery::sql() method, which again shows a fundamental misunderstanding.

6. The databaseQuery::sql() method itself is gibberish.

 

Like I said, there's a lot wrong here, and a lot of it is fundamental.  It's in his best interest to start from scratch and learn it the right way.  Trying to patch what he has now won't address the underlying problems.

Link to comment
Share on other sites

I was following this tutorial when doing the database connection class.

 

http://blog.bluewebtechniques.com/2010/03/10/creating-a-php-oop-database-connection-class/

 

Since then I have sacked that off because I even noticed it was overly complicated for what it was, and start from scratch on php basics via lynda.com tutorials.

 

vicodin with the class example you posted, would it be better practice to have the variables defined in another file and then include it?

 

Also just to clarify if I wanted to call it then all I could have to do is;

 

1.  create object instance from the class

2. and then call the openCon function, as the rest of the data is gathered in the class.

 

# create object instance from the class
$con = new DBConnect();

# and then call the openCon function, as the rest of the data is gathered in the class. 
$con->openCon();

 

I guess I'm going to have to wait until I watch these tutorials to until I fully understand it, as it seems ive got a bit confused along the lines.

 

But would this be the best course of action for a sql query in OO;

 

1. Create a connection to the database.

2. Have another class that has that takes the SQL and does clean it for use.

3. returns the cleaned sql from hacks etc... to the page for use.

 

 

Link to comment
Share on other sites

So something a bit more like this, with config.php holding the connection data as defined constants, this would allow security such as htaccess correct?

 

<?php
    require_once ("config/config.php");
    class DBConnect
    {
       # VARIABLE DATA COMES FROM CONSTANTS DEFINED IN "config.php"
        var $user = dbUsername;
        var $pass = dbPassword;
        var $db = dbName; 
        var $server = dbHostname;

        Private Function setServer($server)
        {
            $this->server = $server;
        }

        Function setUser($user)
        {
            $this->user = $user;    
        }

        Function setPass($pass)
        {
            $this->pass = $pass;
        }

        Function setDb($db)
        {
            $this->db = $db;
        }         

        Function openCon()
        {
            mysql_pconnect($this->server,$this->user,$this->pass);
            mysql_selectdb($this->db);
        }
         
  } 
  ?>

Link to comment
Share on other sites

Tutorials will only explain how to do something.  They won't explain why you want to do that something, at least not from an abstract sense outside of the context of that particular tutorial.  You won't be able to learn true OOP, the kind of stuff employers look for on a resume, from tutorials.  You may get the basics, but that's about it.  There's a fair amount of theory which goes along with it, above and beyond general coding theory.  OOP is far, far more than wrapping some variables and functions in a class and calling it a day.  It's not necessarily hard, but it can get confusing, especially if you don't have a solid foundation of general PHP under your feet.

 

So, like I said before, start with the official manual link I provided above.  That will get you up to speed with modern PHP OO syntax, and some of the basic ideas behind all of it.  From there, if you want to learn it for real, you'll need to get some books:

 

PHP 5 Objects, Patterns, and Practice by Matt Zandstra - http://www.amazon.com/Objects-Patterns-Practice-Experts-Source/dp/143022925X/ref=sr_1_1?ie=UTF8&qid=1304524041&sr=8-1

Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four - http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612/ref=sr_1_1?s=books&ie=UTF8&qid=1304524065&sr=1-1

 

These books don't represent the entirety of what the pros know (there are dozens, if not hundreds, of books on OOP out there, with more being written all the time), but they're the two that will get you thinking as an OO PHP developer.

Link to comment
Share on other sites

Nightslyr is giving you some good advice... You will never be able to think out an OOP problem with out learning the theory behind it... I tried to teach my self OOP through example and I just never really got it. I picked up a few books on it and it was just like a light went off and I understood it.

Link to comment
Share on other sites

Class DBConnect{
var $user = 'username';
var $pass = 'password';
var $db = 'mydb'; 
var $server = 'localhost';

Private Function setServer($server){
$this->server = $server;
}

Function setUser($user){
$this->user = $user;    
}

Function setPass($pass){
$this->pass = $pass;
}
         
Function setDb($db){
    $this->db = $db;
}         

Function openCon(){
mysql_connect($this->server,$this->user,$this->pass);
mysql_selectdb($this->db);
}
         
  } #End Class
  ?>

 

If this is that light. Then it's in need of replacement.

Link to comment
Share on other sites

As someone pointed out before my example is just a very basic database connection script but you only need to call that once. Once you make the connection it stays open till your entire PHP script is finished running. It then closes all by it self which is a feature built into PHP. It is good practice to close the connection by code though.

Link to comment
Share on other sites

What is the whole point of making this script in OO really? Its a simple database connection, yet some people turn it into rocket science and add all these really unnecessary methods of doing a simple thing into a difficult task.

 

You will get lost in your own code.

Link to comment
Share on other sites

Tutorials will only explain how to do something.  They won't explain why you want to do that something, at least not from an abstract sense outside of the context of that particular tutorial.  You won't be able to learn true OOP, the kind of stuff employers look for on a resume, from tutorials.  You may get the basics, but that's about it.  There's a fair amount of theory which goes along with it, above and beyond general coding theory.  OOP is far, far more than wrapping some variables and functions in a class and calling it a day.  It's not necessarily hard, but it can get confusing, especially if you don't have a solid foundation of general PHP under your feet.

 

So, like I said before, start with the official manual link I provided above.  That will get you up to speed with modern PHP OO syntax, and some of the basic ideas behind all of it.  From there, if you want to learn it for real, you'll need to get some books:

 

PHP 5 Objects, Patterns, and Practice by Matt Zandstra - http://www.amazon.com/Objects-Patterns-Practice-Experts-Source/dp/143022925X/ref=sr_1_1?ie=UTF8&qid=1304524041&sr=8-1

Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four - http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612/ref=sr_1_1?s=books&ie=UTF8&qid=1304524065&sr=1-1

 

These books don't represent the entirety of what the pros know (there are dozens, if not hundreds, of books on OOP out there, with more being written all the time), but they're the two that will get you thinking as an OO PHP developer.

 

C++ is a great way to learn oop, specially when you are using Graphics Engines like Ogre3D, they really bring out the true purpose of OOP. The paradigm has alot of similarities with PHP oop, but it does get confusing yes.

 

People really need to familiarize themselves with the terms in OOP, thats what I had most trouble with. But I also see alot of useless crap in OOP that shouldn't even be there specially because you can save so much more time doing it the procedural way.

Link to comment
Share on other sites

I totally agree with you in this case phpSensei but since he is learning OOP I think its good for him to start small and work his way up. Im guessing this is his first language he is learning and C++ on your own is pretty rough if you don't have a back ground in something else. I tried C++ first on my own and failed miserably so I switched to Python and picked up OOP much better there. Everyone is different though.

Link to comment
Share on other sites

I totally agree with you in this case phpSensei but since he is learning OOP I think its good for him to start small and work his way up. Im guessing this is his first language he is learning and C++ on your own is pretty rough if you don't have a back ground in something else. I tried C++ first on my own and failed miserably so I switched to Python and picked up OOP much better there. Everyone is different though.

 

Python is actually great for learning OOP, i don't know how that slipped my mind. I honestly loved their GUI libraries, such as wxwidgets, wxPython and such..

Link to comment
Share on other sites

I've dabbed in a few languages at uni, but we never got enough time to learn it all properly, JavaScript, Java, C#, PHP I sent more time on PHP though and that's the direction I want to go towards, now I'm unemployed with no experience in the industry. The uni spent about 2 lectures teaching OOP which is like  :wtf: it barely covered what a class and object was let alone how to use them. I have just got PHP Objects Patterns and Practice by Matt Zandstra, as an e-book would you say thats a good place to start?

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.