Solved

Fatal error: Class 'Database' not found in C:\wamp\www\oop-beg\ch6-4.php on line 38

Posted on 2013-12-16
5
1,591 Views
Last Modified: 2013-12-17
these are files from php oop tutorial.  I do not understand the way it works yet because there is an error.

Fatal error: Class 'Database' not found in C:\wamp\www\oop-beg\ch6-4.php on line 38

database.php
<?php
//database.php
$GLOBALS['configuration']['db']='secret';
$GLOBALS['configuration']['host']='localhost';
$GLOBALS['configuration']['user']='first';
$GLOBALS['configuration']['pass']='';
$GLOBALS['configuration']['host']=3306;
class DBConnection{
  private function Database(){
    $databaseName=$GLOBALS['configuration']['db'];
    $serverName=$GLOBALS['configuration']['host'];
    $databaseUser=$GLOBALS['configuration']['user'];
    $databasePassword=$GLOBALS['configuration']['pass'];
    $databasePort=$GLOBALS['configuration']['port'];
    $this->connection=mysql_connect($serverName.":".$databasePort,$databaseUser,$databasePassword);
    mysql_set_charset('latin',$this->connection);
    if($this->connection){
      if(!mysql_select_db($databaseName)){
        throw new Exception('Cannot find: "'.$databaseName.'"');
      }
    }
    else
    {
      throw new Exception('Cannot connect to the database.');
    }
  }
  public static function Connect(){
    static $database=null;
    if(!isset($database)){
      $database=new Database();
    }
    return $database->connection;
  }
  
  public static function Reader($query,$connection){
    $cursor=mysql_query($query,$connection);
    return $cursor;
  }
  public static function Read($cursor){
    return mysql_fetch_assoc($cursor);
  }
  public static function NonQuery($query,$connection){
    mysql_query($query,$connection);
    $result=mysql_affected_rows($connection);
    if($result==-1){
      return false;
    }
    return $result;
  }
  
  public static function Query($query,$connection){
    $result=mysql_query($query,$connection);
    return mysql_num_rows($result);
  }
  public static function InsertOrUpdate($query,$connection){
    $result=mysql_query($query,$connection);
    return intval(mysql_insert_id($connection));
  }
}

Open in new window


run this file
ch6-4.php
<?php
//menu model.php
require_once('database.php');
class MenuItem{
  //constructor (not implemented)
  public function __construct(){
    //set undeclared property
  }
  public function __set($property,$value){
    $this->$property=$value;
  }
  //get defined property
  function __get($property){
    if(isset($this->$property)){
      return $this->$property;
    }
  }
  
}

abstract class Menu{
  private $menuid;
  private $parentid;
  private $menuitemid;
  private $menuname;
  private $decription;
  
  public function setMenuID($menuid){$this->menuid=$menuid;}
  public function getMenuID(){return $this->menuid;}
  
  public function setMenuItemID($menuitemid){$this->menuitemid=$menuitemid;}
  public function getMenuName(){return $this->menuname;}
  
  public function setDescription($description){$this->decription=$description;}
  public function getDescription(){return $this->decription;}
  
  function getAllMenuItems($menuid){
    $connection=Database::connect();
    $this->query="select mitm.*, mi.itemname, mi.description,
                        mi.price, mi.picture, mi.servingsize
                        from `menuitemtomenu`
                        as mitm left join `menuitem`
                        as mi on mitm.menuitemid = mi.menuitemid
                        where mitm.menuid=$menuid";
    $menuitemList=Array();
    $cursor=Database::Reader($this->query,$connection);
    while($row=Database::Read($cursor)){
      $menuitem=new MenuItem;
      $menuitem->menuitemid=$row['menuitemid'];
      $menuitem->itemname=$row['itemname'];
      $menuitem->price=$row['price'];
      $menuitem->servingsize=$row['servingsize'];
      $menuitem->description=$row['description'];
      $menuitemList[]=$menuitem;
    }
    return $menuitemList;
  }
}

class MainMenu extends Menu{
  static public $title="<b><font color=blue>Main Menu</font></b>";
  const id=1;
  static public function menutime(){
    return time();
  }
}
class DrinkMenu extends Menu{
  static public $title="<b><font color=lightblue>Drink Menu</font></b>";
  const id=2;
}
class LunchMenu extends Menu{
  static public $title="<b><font color=green>Lunch Menu</font></b>";
  const id=3;
}
class KidsMenu extends Menu{
  static public $title="<b><font color=yellow>Kids Menu</font></b>";
  const id=5;
}
class DessertMenu extends Menu{
  static public $title="<b><font color=red>Dessert Menu</font></b>";
  const id=6;
}
class AppetizerMenu extends Menu{
  static public $title="<b><font color=purple>Appetizer Menu</font></b>";
  const id=7;
}
interface AdjustPortion{
  public function setDinnerPortion($itemobject);
}
interface AdjustPrice{
  public function setDinnerPrices($itemobject);
  public function setHappyHourDrinkPrices($itemobject);
}
final class HappyHourMenu extends DrinkMenu implements AdjustPrice{
  static public $title="<b><font color=orange>Happy Hour Drink Menu</font></b>";
  public function setHappyHourDrinkPrices($menuitemobject){
    $adjusted_price=1;
    $base_price=$menuitemObject->getPrice();
    //make the dinner price 30% less than the normal price
    $adjusted_price=($base_price*0.7);
    return round($adjusted_price,2);
  }
  public function setDinnerPrices($menuitemobject){}
}
final class DinnerMenu extends LunchMenu implements AdjustPortion,AdjustPrice
{
  static public $title="<b><font color=blue>Dinner Menu</font></b>";
  //DinnerMenu inherits ID from LunchMenu
  
  public function setDinnerPortion($menuitemServingSize){
    $adjustment=1;
    $adjusted_servingsize="";
    $portion=explode(" ",$menuitemServingSize);
    //Make the dinner portions 50% bigger than the lunch portion.
    foreach($portion as $subportion){
      if (is_numeric($subportion)){
        $adjustment=$subportion*1.5;
        $adjusted_servingsize=$adjusted_servingsize." ".round($adjustment,2);
      }
      else{
        $adjusted_servingsize=$adjusted_servingsize." ".$subportion;
      }
    }
    return $adjusted_servingsize;
  }
  public function setDinnerPrices($menuitemPrice){
    $adjusted_price=1;
    //make the dinner price 25% more than the lunch price
    try{
      if ($menuitemPrice != 0){
        $adjusted_price=($menuitemPrice * 1.25);
        return round($adjusted_price,2);
      }
      else{
        throw new Exception('MenuItem Price is $0.0');
      }
    }
    catch(Exception $e){
      echo "Caught exception: ".$e->getMessage()."<br>";
    }
  }
  //override the base method to user the adjust price interface
  public function GetAllMenuItems($menuid){
    $connection=Database::Connect();
    $this->query="select mitm.*, mi.itemname, mi.description,
                  mi.price,mi.picture,mi.servingsize 
                  from `menuitemtomenu`
                  as mitm left join `menuitem`
                  as mi on mitm.menuitemid=mi.menuitemid 
                  where mitm.menuid=$menu";
   try{
     // note: recall that the throw new Exception(...) statement is already in the database class in database.php
     $menuitemList=Array();
     $cursor=Database::Reader($this->query,$connection);
     while($row=Database::Read($cursor)){
       $menuitem=new MenuItem;
       $menuitem->menuitemid=$row['menuitemid'];
       $menuitem->itemname=$row['itemname'];
       $menuitem->price=self::setDinnerPrices($row['price']);
       $menuitem->description=$row['description'];
       $menuitem->servingsize=self::setDinnerPortion($row['servingsize']);
       $menuitemList[]=$menuitem;
     }
     return $menuitemList;
   }
   catch(Exception $e){
     echo 'Caught exception: ', $e->getMessage(), "<br>";
   }                  
  }
  public function setHappyHourDrinkPrices($menuitemObject){}
}
//DBMapper handles most of the communication between the model and the database
class DBMapper extends Menu{
  public function Erase($menuitemid){
    try{
      $connection=Database::Connect();
      $this->query="Delect mi.*, mitm.* from `menuitem` as mi
                    LEFT join `menuitemtomenu` as mitm on mitm.menuitemid=mi.menuitemid
                    where mi.menuitemid=$menuitemid";
      $rows=Database::Query($this->query,$connection);
    }
    catch(Exception $e){
      echo "Caught exception in erase method: ".$e->getMessage(),"<br>";
    }
  }
  public function save($data){
    try{
      $connection=Database::Connect();
      if((isset($data["menuid"])&&(isset($data["menuitemid"])))){
      //if the record doesn't exist then we will insert it
      $this->query="select `menuitemid`, `menuid` 
                     from `menuitemtomenu`
                     where `menuitemid`= ".$data['menuitemid']."
                      and `menuid`=".$data['menuid']." LIMIT 1";  
      //note: recall that the throw new Exception(...) statment is already in the
      //database class in database.php
      $rows=Database::Query($this->query,$connection);
      if($rows==0){
        $this->query="insert into `menuitemtomenu` (`menuitemid`,`menuid`) values (
        ".$data['menuitemid'].",".$data['menuid'] . ")";
      }
      $insertId=Database::InsertOrUpdate($this->query,$connection);
      }
      else{
        $menuitem=new MenuItem;
        $menuitem->itemid=$data['menuitemid'];
        $menuitem->itemname=$data['itemname'];
        $menuitem->description=$data['description'];
        $menuitem->servingsize=$data['servingsize'];
        $menuitem->picture=$data['picture'];
        $menuitem->price=$data['price'];
      }
      //check to see if the record already exists in the menuitem table
      //if so we will update, if not we will insert it
      $this->query="select `menuitemid` from `menuitem`
                    where `menuitemid`='" . $menuitem->itemid . "'LIMIT 1";
      //note: recall that the throw new exception(...) statement is already in the
      //database class in database.php
      $rows=Database::Query($this->query,$connection);
      if ($rows>0){
        $this->query="update `menuitem` set
        `itemname`='" . mysql_real_escape_string($menuitem->itemname) . "',
        `description`='".mysql_real_escape_string($menitem->description) . "',
        `servingsize`='".$menuitem->servingsize . "',
        `picture`='".$menuitem->picture."',
        `price`='".$menuitem->price."' where `menuitemid`='".$menuitem->itemid."'";
      }
      else{
        $this->query="insert into `menuitem`
         (`itemname`,`description`,`servingsize`,`picture`,`price`) values (
         '".mysql_real_escape_string($menuitem->itemname)."',
         '".mysql_real_escape_string($menuitem->description)."',
         '".$menuitem->servingsize."',
         '".$menuitem->picture."'
         '".$menuitem->price."')";
      }
      $insertId=Database::InsertOrUpdate($this->query,$connection);
  
  }
  catch(Exception $e){
    echo "Caught exception in the save method: ". $e->getMessage(),"<br>";
  }
}
public function getMenuItemTable(){
  $connection=Database::Connect();
  $this->query="select menuitemid, itemname, description,
     price,picture,sevingsize
     from `menuitem`";
  $menuitemList=Array();
  $cursor=Database::REader($this->query,$connection);
  while($row=Database::Read($cursor)){
    $menuitem=new MenuItem;
    $menuitem->menuitemid=$row['menuitemid'];
    $menuitem->itemname=$row['itemname'];
    $menuitem->price=$row['price'];
    $menuitem->servingsize=$row['servingsize'];
    $menuitem->description=$row['description'];
    $menuitemList[]=$menuitem;
  }
  return $menuitemList;
}



}


$myMenu = new DrinkMenu();

$myMenuItems = $myMenu->getAllMenuItems(2);

foreach ($myMenuItems as $item) {
    echo $item . "<br />";
}

Open in new window

0
Comment
Question by:rgb192
5 Comments
 
LVL 36

Assisted Solution

by:Loganathan Natarajan
Loganathan Natarajan earned 125 total points
ID: 39723177
Actually, your class name is "DBConnection"  in database.php but how do you use Database as class name to create object...
0
 
LVL 30

Assisted Solution

by:Marco Gasi
Marco Gasi earned 125 total points
ID: 39723226
Hi, rgb192. This problem is the same we have pointed out here: http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28314719.html#a39712408

As I said in that thread, and as logudotcom said here, your class name is DBConnection: Database is the name of the class file.
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 125 total points
ID: 39723682
these are files from php oop tutorial.
I don't understand why you would use this for your own learning.  It is a terrible example of PHP object-oriented programming.  You may get it to run by fixing the obvious error(s), but it's one thing to get a piece of code to run, and entirely another to get a piece of code to be encapsulated, maintainable, extensible, reusable and all the other things that are the goals of OOP.  And it fails the common-sense tests of even the simplest procedural programming.  For example, consider this line of code:

throw new Exception('Cannot connect to the database.');

Why did the data base connection fail?  You don't know and this program will not tell you, so you will be stuck in a debugging cycle.  When a data base connection fails, the SQL server has the reason for failure and all you have to do is ask for it!  The obvious omission here is something like this, that would give the programmer a chance of discerning what error might have occurred.

$err = mysql_errno() . ' ' . mysql_error();

And, as if we didn't understand the problem by now, it uses the long-obsolete MySQL Extension.  My guess is that it's a very old example, perhaps something cobbled together from procedural code in the days of PHP 4.

There are a host of other things that create a very bad code smell, too many to waste my time pointing them out one-by-one.  I recommend that you get rid of this terrible example immediately and save yourself from learning the wrong way to do things!

Please consider using the learning resources identified in this article:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html
0
 
LVL 33

Accepted Solution

by:
Slick812 earned 125 total points
ID: 39724496
greetings  rgb192, , according to your ERROR message -
"Fatal error: Class 'Database' not found in C:\wamp\www\oop-beg\ch6-4.php on line 38"

your Fatal Error comes from this line -
$database=new Database();
       (on Line 30 of your TOP code post)

in this method -
public static function Connect(){
    static $database=null;
    if(!isset($database)){
      $database=new Database(); // YOU Have to have the class Database defined Somewhere to use this line
    }
    return $database->connection;
  }

WARNING do not use this Tutorial ! ! !
I agree with Ray about this code work being "terrible example of PHP object-oriented programming", and tell you -
DO NOT USE THIS TUTORIAL ! ! !
I could list at least 20 lines and code operations that YOU should NOT LEARN !

Learning the advantages of PHP OOP and using the OOP to make your web site more productive with LESS CODE WORK, requires you to do more than just copy and paste code as you seem to do. You must change the code to test DIFFERENT OPTIONS that you can use in OOP code work for BETTER page results, You definitively will NOT get better page results using the code work of this tutorial.
0
 

Author Closing Comment

by:rgb192
ID: 39725130
I will be asking questions about
PHP-Advanced-and-Object-oriented-Programming-Visual-QuickPro-Guide
which Ray recommends.

Thanks.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

746 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now