PHP Classes

File: summary.php

Recommend this page to a friend!
  Classes of Jason Johnson   MySQL Model   summary.php   Download  
File: summary.php
Role: Example script
Content type: text/plain
Description: Summary
Class: MySQL Model
Wrap the access to MySQL table rows using objects
Author: By
Last change: Example revised to reflect changes made in the base class.
Date: 18 years ago
Size: 5,898 bytes
 

Contents

Class file image Download
<?php

    $connection
= mysql_connect(
       
"localhost",
       
"root",
       
""
   
);
   
   
mysql_select_db(
       
"test",
       
$connection
   
);

   
//////////////////////////////////////////////////////////////////////
    //
    // MySQL tables used in the following examples.
    //
    //////////////////////////////////////////////////////////////////////
    /*
        CREATE TABLE `categories` (
          `id` int(11) NOT NULL auto_increment,
          `title` varchar(255) NOT NULL default '',
          `description` varchar(255) NOT NULL default '',
          PRIMARY KEY (`id`)
        ) ENGINE=MyISAM;
       
        INSERT INTO `categories`(
            `title`,
            `description`
        ) VALUES (
            'General',
            'This is the general category.'
        );
       
        CREATE TABLE `articles` (
          `id` int(11) NOT NULL auto_increment,
          `category_id` int(11) NOT NULL default '0',
          `title` varchar(255) NOT NULL default '',
          `introduction` varchar(255) NOT NULL default '',
          `article` varchar(255) NOT NULL default '',
          PRIMARY KEY (`id`)
        ) ENGINE=MyISAM;

        INSERT INTO `articles`(
            `category_id`,
            `title`,
            `introduction`,
            `article`
        ) VALUES (
            1,
            'Hello, World!',
            'The introduction of the lame hello, world article.',
            'The article body of the lame hello, world article.'
        );

        CREATE TABLE `comments` (
          `id` int(11) NOT NULL auto_increment,
          `article_id` int(11) NOT NULL default '0',
          `comment` varchar(255) NOT NULL default '',
          PRIMARY KEY (`id`)
        ) ENGINE=MyISAM;
       
        INSERT INTO `comments`(
            `article_id`,
            `comment`
        ) VALUES (
            1,
            'First comment!'
        );
       
        INSERT INTO `comments`(
            `article_id`,
            `comment`
        ) VALUES (
            1,
            'Second comment!'
        );
    */
    //////////////////////////////////////////////////////////////////////
   
   
   
   
    //////////////////////////////////////////////////////////////////////
    //
    // Extend the class using a database table name as class name. The class
    // name need not be the exact capitalization of the table name.
    //
    //////////////////////////////////////////////////////////////////////

        // Require the class to be extended.
       
require_once("mysql_model.class.php");

        class
Articles extends MySQL_Model
       
{
           
// Handle id and auto arguments in the constructor.
           
function Articles($id = 0, $auto = "")
            {
               
// Initialize the Model class with proper arguments.
               
$this -> init($id, $auto);
               
               
$this -> belongs_to_one(
                   
"categories", // The `categories` table.
                   
"id", // The foreign key in the `categories` table.
                   
"category_id" // The key in the `articles` table.
               
);
               
               
$this -> has_many(
                   
"comments", // The `comments` table.
                   
"article_id" // The foreign key in the `comments` table.
                    // Assumed is the auto key in the `articles` table.
               
);
            }
        }
   
   
//////////////////////////////////////////////////////////////////////
   
   
   
   
    //////////////////////////////////////////////////////////////////////
    //
    // Find all articles.
    //
    //////////////////////////////////////////////////////////////////////
   
       
$a = new Articles();
       
$articles = $a -> find();
       
       
// Loop through the articles, printing them to the screen.
       
for($i = 0; $i < count($articles); $i++)
        {
            echo
$articles[$i]["categories"]["title"] . "\t";
            echo
$articles[$i]["title"] . "\n";
        }
   
   
//////////////////////////////////////////////////////////////////////
   
   
   
   
    //////////////////////////////////////////////////////////////////////
    //
    // Attempt to create a new record. Cause an error to be generated when
    // `category_id` is not provided.
    //
    // NOTE: If a column does not allow NULL values, it is considered by
    // the MySQL_Model class to be required.
    //
    // The only thing we must do after catching the error is set `category_id`
    // to some value and attempt to save() again. The data persists after
    // the call to save().
    //
    // NOTE: If you provide an `id` to the Articles constructor and eventually
    // call save(), this will update the record, not create a new one.
    //
    //////////////////////////////////////////////////////////////////////
   
       
$a = new Articles();
       
       
// Set fields, leaving one blank to cause an error.
       
$a -> set("category_id", 0);
       
$a -> set("title", "...");
       
$a -> set("introduction", "...");
       
$a -> set("article", "...");
       
       
// Save and catch errors in data validation.
       
if(!$a -> save())
        {
           
// Print the error array to the screen.
           
print_r($a -> error());
        }
       
   
//////////////////////////////////////////////////////////////////////
   
   
    //////////////////////////////////////////////////////////////////////
    //
    // Display managed data structure.
    //
    // Assuming an Article with the `id` '1' exists, this will look in the
    // `categories` and `comments` tables and attach all records matching:
    //
    // "articles.category_id = categories.id"
    // and
    // "articles.id = comments.article_id"
    //
    // This is considered a lazy join due to the absence of an actual join
    // clause in the sql. This allows for much simpler code and the ability to
    // greatly modify the behavior of values returned by this kind of join.
    //
    // You will note that after printing out the fields array there is a new
    // field titled 'comments' which contains an array of values found in the
    // `comments` table.
    //
    // You will also notice a single array has been attached called
    // `categories` which contains the record found in the `categories` table.
    //
    // NOTE: When using has_many(), the attached array will be an array of
    // assoc array's. When using has_one(), the attached array will be an
    // assoc array.
    //
    // NOTE: You can call these functions as many times as you'd like. It
    // simply continues to add to the fields.
    //
    //////////////////////////////////////////////////////////////////////
   
       
$a = new Articles(1);
       
print_r($a -> get_fields());
   
   
//////////////////////////////////////////////////////////////////////
   
   
   
mysql_close(
       
$connection
   
);
?>