Wrox Programmer Forums
|
BOOK: Professional PHP 5 ISBN: 978-0-7645-7282-1
This is the forum to discuss the Wrox book Professional PHP5 by Ed Lecky-Thompson, Heow Eide-Goodman, Steven D. Nowicki, Alec Cove; ISBN: 9780764572821
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Professional PHP 5 ISBN: 978-0-7645-7282-1 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old October 11th, 2008, 11:46 PM
Registered User
 
Join Date: Oct 2008
Posts: 2
Thanks: 0
Thanked 2 Times in 2 Posts
Send a message via MSN to teleboobee
Default Chapter 7 for MySQL

after I read gorillapoop's post, http://p2p.wrox.com/topic.asp?TOPIC_ID=44613 , I tried the code, but it is not working for me. I do some modification for gorillapoop's code and make it works for me. The code I tested in WAMP Environment with MYSQL and assume that host = localhost, user = root, with no password, database_name = test

codes as following:

//--------------------------------------------------------------
// sql.php
<?php
class sql {
  private $result_rows; # Result rows hash
  private $query_handle; # db: the query handle
  private $link_ident; # db: the link identifier

  public function __construct() {
    $hostname = 'localhost';
    $username = 'root';
    $password = '';
    $database = 'test';
    if (!$this->link_ident){
            $this->link_ident=mysql_connect($hostname, $username, $password);
    }
    mysql_select_db($database);
  }

  public function query($sql, $code_return_mode = 0) {

    $result=mysql_query($sql,$this->link_ident);
    if (!$result){
        error_log("QUERY FAILED: $sql\n");
        echo ("QUERY FAILED: $sql\n");
        return(0);
    }else{
        $num=mysql_numrows($result);
        for ($i=0; $i<$num; $i++){
            $return_array[$i] = mysql_fetch_array($result);
        }
        $this->result_rows = $return_array;
    }
    return(1);
  }

  public function get_result($row_num, $column_name) {
    return ($this->result_rows[$row_num][$column_name]);
  }

  public function get_row_hash($row_num) {
    return ($this->result_rows[$row_num]);
  }

  public function get_table_hash() {
    return $this->result_rows;
  }

  public function done($close_connection = 0) {
    if ($close_connection) {
      mysql_close ($this->link_ident);
    }
  }
};
?>


//--------------------------------------------------------------
// GenericObject.php

<?php

require_once 'sql.php';

$debug = 1;

class GenericObject {

  # Member Variables

  private $id;
  private $table_name;

  private $database_fields;
  private $loaded;
  private $modified_fields;

  # Methods

  public function Reload() {
    $sql = new sql(0);
    $id = $this->id;
    $table_name = $this->table_name;
    $sql->query("SELECT * FROM ".$table_name ." WHERE id=".$id."");



    //for debug only --------------------------------------------
    if($debug){
        print "SELECT * FROM ".$table_name ." WHERE id=".$id."";
    }
    //-----------------------------------------------------------



    $result_fields = $sql->get_row_hash(0);
    $this->database_fields = $result_fields;
    $this->loaded = 1;
    if (sizeof($this->modified_fields) > 0) {
      foreach ($this->modified_fields as $key => $value) {
        $this->modified_fields[$key] = false;
      };
    };
  }

  private function Load() {
    $this->Reload();
    $this->loaded = 1;
  }

  public function ForceLoaded() {
    $this->loaded = 1;
  }

  public function GetField($field) {
    if ($this->loaded == 0) {
      $this->Load();
    };
    return $this->database_fields[$field];
  }

  public function GetAllFields() {
    if ($this->loaded == 0) {
      $this->Load();
    };
    return($this->database_fields);
  }

  public function GetID() {
    return $this->id;
  }

  public function Initialize($table_name, $tuple_id = "") {
    $this->table_name = $table_name;
    $this->id = $tuple_id;
  }

  public function SetField($field, $value) {
    if ($this->loaded == 0) {
      if ($this->id) {
        $this->Load();
      };
    };
    $this->database_fields[$field] = $value;
    $this->modified = 1;
    $this->modified_fields[$field] = true;
  }

  public function Destroy() {
    $id = $this->id;
    $table_name = $this->table_name;
    if ($id) {
      $sql = new sql(0);
      $stmt = "DELETE FROM " . $table_name . " WHERE id=\'" . $id . "\'";
      $sql->query($stmt);
    };
  }

  public function Save() {
    $id = $this->id;
    $table_name = $this->table_name;
    $sql = new sql(0);
    if (!$id) {
      $this->loaded = 0;
    };
    if ($this->loaded == 0) {
      # assume this is a new entity
      $stmt = "INSERT INTO " . $table_name ." (";
      foreach ($this->database_fields as $key => $value) {
        if (!is_numeric($key)) {
          $key = str_replace("'", "\'", $key);
          if ($value != "") {
            $stmt .= $key.",";
          };
        };
      };
      # Chop last comma
      $stmt = substr($stmt,0,strlen($stmt)-1);
      $stmt .= ") VALUES (";
      foreach ($this->database_fields as $key => $value) {
        if (!is_numeric($key)) {
          if ($value != "") {
            $value = str_replace("'", "\'", $value);
            $stmt .= "'$value',";
          };
        };
      };
      # Chop last comma
      $stmt = substr($stmt,0,strlen($stmt)-1);
      $stmt .= ")";
    } else {
      $stmt = "UPDATE " . $table_name ." SET ";
      foreach ($this->database_fields as $key => $value) {
        if (!is_numeric($key)) {
          if ($this->modified_fields[$key] == true) {
            $value = str_replace("'", "\'", $value);
            if ($value == "") {
              $stmt .= $key." = NULL, ";
            } else {
              $stmt .= $key." = '$value', ";
            };
          };
        };
      };
      # Chop last comma and space
      $stmt = substr($stmt,0,strlen($stmt)-2);
      $stmt .= " WHERE id='$id'";
    };
    $return_code = $sql->query($stmt, 1);
    if ($this->loaded == 0) {
      # Try to get the ID of the new tuple.
      $stmt = "SELECT MAX(id) AS id FROM $table_name WHERE ";
      foreach ($this->database_fields as $key => $value) {
        if (!is_numeric($key)) {
          if ($value) {
            if ($this->modified_fields[$key] == true) {
              $value = str_replace("'", "\'", $value);
              $stmt .= "\"$key\" = '$value' AND ";
            };
          };
        };
      };
      # Chop last " AND " (superfluous)
      $stmt = substr($stmt,0,strlen($stmt)-5);
      $sql->query($stmt);
      $result_rows = $sql->get_table_hash();
      $proposed_id = $result_rows[0]['id'];
      if ($proposed_id > 0) {
        $this->loaded = 1;
        $this->id = $proposed_id;
        return true;
      } else {
        return false;
      };
    };
    return($return_code);
  }
};


//--------------------------------------------------------------
// test_sql.php
//this is for test the sql class

<?php
require_once 'sql.php';

$sql = new sql();
$sql->query("SELECT * FROM user");
$result_rows = $sql->get_table_hash();
for($i = 0;$i < sizeof($result_rows)-1; $i++){

    print ("Data Type : " . $result_rows[$i]."\n<br>");
    print ("ID : " . $result_rows[$i]['id'] . "\n<br>");
    print ("UserName : " . $result_rows[$i]['username'] . "\n<br>");
    print ("FirstName : " . $result_rows[$i]['first_name'] . "\n<br>");
    print ("LastName : " . $result_rows[$i]['last_name'] .
 "\n<br>==========================<br><br>");
}

$sql->done(1);

?>


//--------------------------------------------------------------
// user.php

<?php

require_once 'GenericObject.php';

class User extends GenericObject {
 public function __construct($id) {
         $this->initialize("user", $id);
 }
}
?>


//--------------------------------------------------------------
// userteset.php
// this is for user test

<?php
#require_once("GenericObject.php");
require_once("user.php");

 $objUser = new User(1);
 $strUsername = $objUser->GetField("last_name");
 print $strUsername;
?>


//--------------------------------------------------------------
// user.sql
// this is MYSQL Statement for user table,
// I use this in phpAdmin

CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(32) collate utf8_unicode_ci NOT NULL,
  `first_name` varchar(64) collate utf8_unicode_ci NOT NULL,
  `last_name` varchar(64) collate utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=7 ;


INSERT INTO `user` (`id`, `username`, `first_name`, `last_name`) VALUES
(1, 'ed', 'Ed', 'Lecky-Thompson'),
(2, 'steve', 'Steve', 'Nowicki'),
(3, 'alec', 'Alec', 'Cove'),
(4, 'heow', 'Heow', 'Eide-Goodman'),
(5, 'john', 'John', 'Doe'),
(6, 'jane', 'Jane', 'Doe');


//------------------------------------------------------
I hope this can help.
Thanks.









[email protected]
The Following User Says Thank You to teleboobee For This Useful Post:
shegxzyl (August 25th, 2009)
 
Old October 13th, 2008, 11:12 PM
Registered User
 
Join Date: Oct 2008
Posts: 2
Thanks: 0
Thanked 2 Times in 2 Posts
Send a message via MSN to teleboobee
Default

//Please remove the debug part if you do not want that information

// GenericObjectCollection.php

<?php

  require_once 'sql.php';


  class GenericObjectCollection {

    # Member Variables
    var $table_name;
    var $class_name;

    var $items_per_page;
    var $item_count = 0;

    var $id_array;

    var $obj_array;

    function __construct($table_name, $class_name) {
      $this->table_name = $table_name;
      $this->class_name = $class_name;
    }

    function AddTuple($id) {
      if (!$this->id_array) {
        $this->id_array = array();
      };
      array_push($this->id_array, $id);
      $this->item_count = sizeof($this->id_array);
    }

    function SetPageSize($items_per_page) {
      $this->items_per_page = $items_per_page;
    }

    function GetItemCount() {
      return $this->item_count;
    }

    function GetNumPages() {
      return(ceil($this->item_count / $this->items_per_page));
    }

    function _GetCommaSeparatedIDList($start_lim = 0, $end_lim = -1) {
      $s = "";
      if ($end_lim == -1) {
        $end_lim = sizeof($this->id_array)-1;
      };
      for ($i=$start_lim; $i<=$end_lim; $i++) {
        if (is_numeric($this->id_array[$i])) {
          $s = $s . $this->id_array[$i] . ",";
        };
      };
      $s = substr($s, 0, strlen($s) - 1);
      return $s;
    }

    function _GetIndexFromTupleID($tuple_id) {
      $index = -1;
      for ($i=0; $i<=sizeof($this->id_array)-1; $i++) {
        if ($this->id_array[$i] == $tuple_id) {
          $index = $i;
        };
      };
      return $index;
    }

    function PopulateObjectArray($page_num = 0) {
      $items_per_page = $this->items_per_page;
      if ($this->item_count > 0) {
        if ($page_num > 0) {
          $start_lim = ($items_per_page * ($page_num - 1));
          $end_lim = ($start_lim + $items_per_page) - 1;
          if ($end_lim > ($this->item_count-1)) {
            $end_lim = $this->item_count - 1;
          };
          $stmt = "SELECT * FROM " . $this->table_name . " WHERE id IN (" . $this->_GetCommaSeparatedIDList($start_lim, $end_lim). ")";
        } else {
          $stmt = "SELECT * FROM " . $this->table_name . " WHERE id IN (" . $this->_GetCommaSeparatedIDList(). ")";
        };
        # Perform SQL query
        $sql = new sql(0);
        $sql->query($stmt);
        $result_rows = $sql->get_table_hash();

        for ($i=0; $i<=sizeof($result_rows)-1; $i++) {
          $this_row = $result_rows[$i];
          $this_db_row_id = $this_row['id'];
          $this_index = $this->_GetIndexFromTupleID($this_db_row_id);
          if ($this_index >= 0) {
            $refObjArrayIndexObj = &$this->obj_array[$this_index];
            $s = "\$refObjArrayIndexObj = new " . $this->class_name . "(" . $this_db_row_id . ");";



//For debug only********************************************** *************
    if (1){
    print "Debug Display: s = ".$s ."<br>";
      }
//End debug ************************************************** *************

            eval($s);

            $refObjArrayIndexObj->ForceLoaded();
            foreach ($this_row as $key => $value) {
              if (!(is_numeric($key))) {


//For debug only********************************************** *************
    if (1){
    print "Debug Display: ". $key . " = " . $value ."<br>";
      }
//End debug ************************************************** *************

                $refObjArrayIndexObj->SetField($key, $value);

              };
            };
          };
        };
      };
    }

    function RetrievePopulatedObjects($page_num = 0) {


//For debug only********************************************** *************
    if (1){
    print "Debug Display: page_num = " . $page_num ."<br>";
      }
//End debug ************************************************** *************


      if ($page_num > 0) {
        $items_per_page = $this->items_per_page;
        # Calculate start and end limits from page number.
        $start_lim = ($items_per_page * ($page_num - 1));
        $end_lim = ($start_lim + $items_per_page) - 1;
          if ($end_lim > ($this->item_count-1)) {
            $end_lim = $this->item_count - 1;
          };
      } else {
        $start_lim = 0;
        $end_lim = $this->item_count - 1;
      };
      $return_array = array();
      $counter = 0;
      for ($i=$start_lim; $i<=$end_lim; $i++) {
        $return_array[$counter] = $this->obj_array[$i];
        $counter++;
      };
      return($return_array);
    }
  }
?>

//================================================== ==========
//UserHome.php

<?php
require_once 'GenericObjectCollection.php';
require_once 'user.php';

class UserHome {

  var $items_per_page = 12;
  var $item_count;
  var $page_count;

  public function __construct() {
    return(true); # No useful constructor in a Home Class
  }

  public function SetItemsPerPage($items_per_page) {
    $this->items_per_page = $items_per_page;
  }

  public function GetItemCount() {
    return ($this->item_count);
  }

  public function GetPageCount() {
    return ($this->page_count);
  }

  public function GetAllUsersWithFirstNameBeginningWith($strLetter, $page_num=1) {
    $dbc = new GenericObjectCollection("user", "User");
    $sql = new sql();
    $strLetter = strtolower($strLetter);
    $sql->query("SELECT id FROM user WHERE lower(first_name) LIKE '".$strLetter."%'");

//For debug only********************************************** *************
if (1){
print "Debug Display-sql: "."SELECT id FROM user WHERE lower(first_name) LIKE '".$strLetter."%'"."<br>";
}
//End debug********************************************* *******************


    $result_rows = $sql->get_table_hash();
    for ($i=0; $i<=sizeof($result_rows)-1; $i++) {
      $dbc->AddTuple($result_rows[$i]['id']);


//for debug only********************************************** *************
if (1){
print "Debug Display-result_rows: ".$result_rows[$i]['id']."<br>";
  }
//End debug ************************************************** *************

    };
    $dbc->SetPageSize($this->items_per_page);
    $dbc->PopulateObjectArray($page_num);
    $objArray = $dbc->RetrievePopulatedObjects($page_num);

    $this->item_count = $dbc->GetItemCount();

//for debug only********************************************** *************
if (1){
print "Debug Display: item_count = ". $this->item_count."<br>";
  }
//End debug ************************************************** *************

    $this->page_count = $dbc->GetNumPages();

//for debug only********************************************** *************
if (1){
print "Debug Display: page_count = ". $this->page_count ."<br>";
  }
//End debug ************************************************** *************

    return($objArray);
  }
}
?>

//================================================== ==========
// test_userhome.php

<?php

require_once 'UserHome.php';

$uH = new UserHome();

$arUsers = $uH->GetAllUsersWithFirstNameBeginningWith('j');


//For debug only********************************************** *************
if ($debug){
print "Debug Display:Size of arUsers = ". sizeof($arUsers)."<br>";
  }
//End debug ************************************************** *************


for ($i=0; $i<sizeof($arUsers); $i++ ){
  print $arUsers[$i]->GetField("first_name") . " ".
        $arUsers[$i]->GetField("last_name") . "<br>\n";
};

?>

//================================================== ===========
//Enjoy it in MYSQL

[email protected]
The Following User Says Thank You to teleboobee For This Useful Post:
shegxzyl (August 25th, 2009)





Similar Threads
Thread Thread Starter Forum Replies Last Post
MySQL conversions - chapter 7 gorillapoop BOOK: Professional PHP 5 ISBN: 978-0-7645-7282-1 2 February 15th, 2011 11:02 AM
Chapter 16 Beginning php5, apache, mysql, web dev charlie2450 Beginning PHP 1 September 13th, 2008 02:07 AM
php won't inseret in MYSQL chapter 3 mAhmed BOOK: Beginning PHP, Apache, MySQL Web Development ISBN: 978-0-7645-5744-6 0 March 28th, 2005 01:03 PM
Chapter 9 - Apache, PHP and Mysql Development AMP_Engineer Beginning PHP 1 September 25th, 2004 11:27 AM
Second MySQL Chapter sethtrain BOOK: Beginning PHP4/PHP 5 ISBN: 978-0-7645-4364-7; v5 ISBN: 978-0-7645-5783-5 0 June 13th, 2003 08:18 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.