tags:

views:

66

answers:

2
+3  Q: 

OO database class

Hi everyone. I'm trying to learn object oriented programming more clearer by creating a database class in PHP.

This is what i have right now. I'm getting an error about $mysqli being an undefined variable when i try to call it using $db->query();

Please explain how to make the variable $mysqli defined.

<?php

class phpDatabaseClass {

 public function __construct()
 {
  $mysqli = new mysqli(DBhost, DBusername, DBpassword, DBname);
 }

 public function query()
 {
  $sql = 'select * from users';
  $results = $mysqli->query($sql);

  if(($results->num_rows) > 0) 
  {
   echo 'We have: '.$results->num_rows;
  }
 }

}

?>

In another file i am instantiating the object and then calling a function like this:

 require 'phpDatabaseClass.php';
 define('DBhost', 'localhost');
 define('DBusername', 'root');
 define('DBpassword', 'root');
 define('DBname', 'campbellCustomCoatings');


 $db = new phpDatabaseClass();
 $db->query();
+2  A: 

The problem I can see is trying to make $mysqli persist between function calls inside the same object.

What needs to be done is to have the variable stored as an instance variable, which are qualified by $this->[VARIABLE]:

<?php

class phpDatabaseClass {

 public function __construct()
 {
  $this->mysqli = new mysqli(DBhost, DBusername, DBpassword, DBname);
 }


 public function query()
 {
  $sql = 'select * from users';
  $results = $this->mysqli->query($sql);

  if(($results->num_rows) > 0) 
  {
   echo 'We have: '.$results->num_rows;
  }
 }

}

?>

I'd look into using PDO.

amphetamachine
You may need to define the property as well :P
alex
+2  A: 

Your instance of mysqli will need to be a member of your class, have a look here...

class phpDatabaseClass {
 private $mysqli;
 public function __construct()
 {
  $this->mysqli = new mysqli(DBhost, DBusername, DBpassword, DBname);
 }

 public function query()
 {
  $sql = 'select * from users';
  $results = $this->mysqli->query($sql);

  if(($results->num_rows) > 0) 
  {
   echo 'We have: '.$results->num_rows;
  }
 }

}

Also, because you are learning, try extending the PDO class to learn about inheritance.

Also, slightly tangential, but generally constants are named with ALL_CAPS_WITH_UNDERSCORE_SEPARATORS.

Also, database stuff in global defines can be risky, as every piece of PHP can access it. I know WordPress does it, but trust me that the quality of its code is questionable. Its popularity however, is without doubt huge.

alex
I thought the purpose of Defining constants was so that they can't be changed. Are you saying it's risky because it can be changed or because it can be viewed by a user? What would be a better solution?
Catfish
@Catfish Only risky because they are globally available. See this question too http://stackoverflow.com/questions/593440/what-is-the-best-way-to-store-configuration-variables-in-php
alex