tags:

views:

229

answers:

4

So I am trying to understand OOP more and use it.

The following code was written before i started using OOP.

//loop through all the users 
$game = "$_POST[Game]_teams";
$result = mysql_query("SELECT username FROM `users`") or die(mysql_error());
while( $row=mysql_fetch_assoc($result) )
{
    $u[] = $row['username'];
}

I have put the query into my database page like following:

   function selectAllUsers()
   {
        $q = "SELECT username FROM ".TBL_USERS."";
        mysql_query($q, $this->connection);
   }

I'm a little confused about how the rest could be different? Would it be? Is it possible for anyone to help me without more code or understanding of my structure?

+3  A: 

Each function in your class should do one task and one task only and should be named appropriately.

Your selectAllUsers function should just select all users, as you have done so,

function selectAllUsers() {
 $q = "SELECT username FROM ".TBL_USERS."";
 return mysql_query($q, $this->connection);
}

However, I added a return keyword, to return the resource which we can use later on.

You could then have a function called generateUserArray, which would populate an array of user's using the returned MySQL resource from the selectAllUsers function.

function generateUserArray() {
 $u = array();
 $result = $this->selectAllUsers();
 while( $row=mysql_fetch_assoc($result)) {
  $u[] = $row['username'];
 }
 return $u;
}

With more information regarding your question, the more answers you will receive in regards to what your trying to accomplish, or clear up any confusion.


First, here is my test table (users) from my test database (login),

mysql> select * from users;
+-----------+-----------+
| Name      | Password  |
+-----------+-----------+
| aforloney | whatsup   |
| pam       | qwerty    |
+-----------+-----------+
2 rows in set (0.15 sec)

And here is my test class in MyClass.php

class MyClass {

 function connect() {
  mysql_connect("localhost","root","password");
  mysql_select_db("login");
 }

 function selectAllValues() {
  $q = "SELECT * FROM users";
  return mysql_query($q);
 }

 function printAllValues() {
  $result = $this->selectAllValues();
  while ($row = mysql_fetch_assoc($result)) {
   echo $row['Name'] . " and " . $row['Password'] . "<br/>";
  }
 }
}

Which you could then invoke from a Main class like so,

class Main {    

// other variables...

// __construct is an object's constructor, it's what gets called when 
// you create a new Main object

  function __construct() {

   $myClass = new MyClass();
   $myClass->connect();
   $myClass->selectAllValues();
   $myClass->printAllValues(); 

  }
}

And then called,

$m = new Main(); // will invoke the __construct function

Which will output to the browser,

 aforloney and whatsup
 pam and qwerty

As a side note, just to avoid any other confusion, my MyClass and Main example were two classes inside the same PHP file. If you were to use the above code examples and try to create a MyClass object, it would throw an error.

If you had wanted to instantiate an object that is defined in another class, you would need an include statement.

So with two different PHP files, I would change my code for the Main class like so,

<?php
include ('MyClass.php'); 
class Main {
 ...
}
?>
Anthony Forloney
Not sure if this is what the OP had wanted, but I decided to post my answer anyways. If the answer is not what the OP had intended, I will remove the post.
Anthony Forloney
I think this is helpful. How would i access this function on my other page?$database->generateUserArray() ???Would that list all the users for me?
Luke
I will update my answer.
Anthony Forloney
I tried to mimic to the best of my abilities your example, but I am sure you can edit to your own needs.
Anthony Forloney
I am over the moon with that answer. That has really put me where I need to be. Completely understand the existing code I had now. Thankyou very much
Luke
Not a problem, happy OOP'ing :)
Anthony Forloney
Even thought this guy has no idea what defines object oriented programming...
RandyMorris
A: 

Actually I would say your example shifts from structural to functional but I would not say makes an example of object oriented.

an object oriented example would be more like:

class user {

public $username;
public $password;

public function showUsername(){
  echo 'Username is '.$this->username;
}

public function showPassword(){
  echo 'Password is '.$this->password;
}
}
RandyMorris
Wow, alot of nerd rage it seems on this site. I thought the idea was to downvote misinformation, not difference of opinion.
RandyMorris
+2  A: 

First of all, you should consider switching to PDO (see php.net). It has by nature a more OOP-ish approach and provides a better and more intuitive API plus lots of other features contrary to the mysql_* functions.

Extremely simple example: Here we are fetching user data from the database and populate User-objects with that data.

<?php
class UserMapper {
    protected $connection;
    public function __construct(PDO $connection) {
        $this->connection = $connection;
    }

    public function findAll() {
       $statement = $this->connection->prepare("SELECT * FROM users");
       $statement->execute();
       return $statement->fetchAll(PDO::FETCH_CLASS, 'User');
    }
}

class User {
    public $name;
    public $email;
    public $password;
}

$connection = new PDO('mysql:dbname=users;host=127.0.0.1', 'root', 'root');
$userMapper = new UserMapper($connection);

$users = $userMapper->findAll();
print_r($users);
Hanse
A: 

I've in the past used some php metaprogramming to accomplish this. http://iain.codejoust.com/2010/02/very-basic-php-orm/

The general idea is to create a model class, and setup a php __call handler enabling the database class intercepts the method called, sets up the arguments, then the Model class returns a SQL string created from the arguments and the function in the Model.

When the function is called, the result is a PDO object with the results of the SQL query contained within.

You also can take a look at PHP ORMs such as http://www.doctrine-project.org/ to provide a very OOP enabled interface with less effort.

CodeJoust