PHP Classes

File: MySQLTable.php

Recommend this page to a friend!
  Classes of Ingvar Stepanyan   Cached Virtual Array   MySQLTable.php   Download  
File: MySQLTable.php
Role: Example script
Content type: text/plain
Description: Simple demo for id-data MySQL table
Class: Cached Virtual Array
Base class for implementing persistent arrays
Author: By
Last change: - Changes to structure according to CachedArray 1.1
- Prettified
Date: 13 years ago
Size: 2,463 bytes
 

Contents

Class file image Download
<?php
include 'CachedArray.class.php';

class
MySQLTable extends CachedArray
{
    private
$table, $id, $data, $link;

    function
__construct($Connection, $AutoFlush=TRUE)
    {
       
parent::__construct($AutoFlush);
       
preg_match('/^(([^:@\/]*):)?([^@\/]*)?(@(\w*))?\/([^\/]+)\/(.+)\(([^,]+),([^)]+)\)$/',$Connection,$matches) or die('Bad connection string');
       
$this->link = mysql_connect($matches[5], $matches[2], $matches[3], TRUE);
       
mysql_select_db($matches[6], $this->link);
       
$this->table = $matches[7];
       
$this->id = $matches[8];
       
$this->data = $matches[9];
    }

    function
__destruct()
    {
       
parent::__destruct();
       
mysql_close($this->link);
    }

    function
getItem($Index)
    {
       
$Query = mysql_query("SELECT `{$this->data}` FROM `{$this->table}` WHERE `{$this->id}`='{$Index}'", $this->link);
       
$Fetch = mysql_fetch_row($Query);
        return
$Fetch[0];
    }

    function
setItem($Index, $Value)
    {
       
mysql_query('UPDATE `'.$this->table.'` SET `'.$this->data.'`=\''.mysql_real_escape_string($Value, $this->link).'\' WHERE `'.$this->id.'`='.$Index, $this->link);
    }

    function
addItem($Value=NULL)
    {
       
mysql_query('INSERT INTO `'.$this->table.'`(`'.$this->data.'`) VALUES(\''.mysql_real_escape_string($Value, $this->link).'\')', $this->link);
        if(
mysql_errno($this->link)) { die(mysql_error($this->link)); }
        return
mysql_insert_id($this->link);
    }

    function
delItem($Index)
    {
       
mysql_query("DELETE FROM `{$this->table}` WHERE `{$this->id}`='{$Index}'", $this->link);
    }

    function
hasItem($Index)
    {
       
$Query = mysql_query("SELECT COUNT(*) FROM `{$this->table}` WHERE `{$this->id}`='{$Index}'", $this->link);
       
$Fetch = mysql_fetch_row($Query);
       
mysql_free_result($Query);
        return
$Fetch[0] > 0;
    }

    function
items()
    {
       
$Query = mysql_query('SELECT `'.$this->id.'` FROM `'.$this->table.'`',$this->link);
       
$Result = array();
        while(
$Fetch = mysql_fetch_row($Query)) { $Result[]=$Fetch[0]; }
        return
$Result;
    }
}

$table = new MySQLTable('root:/test/datas(id,data)', TRUE);
$table[] = 'igor';
echo
'<table border=1>';
foreach(
$table as $index => $value) echo '<tr><td>' . $index . '</td><td>' . $value . '</td></tr>';
echo
'</table>';