Barnaby Norman

MySQL Genie - Source Code

Barnaby Norman Home Page | Site Map | Family Norman Genealogy Site | Contact Me

GenieDataReader class

This class accesses the database and returns the data in an array format. It consists of three database query functions, a shared function that brings back database or table names and a constructer that creates the database session, held in the class variable $mysqli.

Full source code for GenieDataReader.class

<?php

class GenieDataReader
{
    private 
$mysqli;
    
    function 
__construct($host, $user, $pass)
    {    
        
$this->mysqli = new mysqli($host, $user, $pass);
    }
    
    function 
getDBorTables($type)
    {    
        
// Returns an array of database or table names
        
$sql "SHOW $type";
        
        if (
$result $this->mysqli->query($sql)) 
        {
            
// Get a list of tables
            
while ($row $result->fetch_row()) 
            {
                
$data[] = $row[0];
            }
        }
        
        return 
$data;
    }
    
    function 
listDatabases()
    {    
        
// An interface to get array of databases
        
return $this->getDBorTables("DATABASES");
    }

    function 
listTables($database)
    {
        
// An interface to get array of tables
        
        // Database must be selected first
        
$sql "USE $database";
        
        
$this->mysqli->query($sql);
        
        return 
$this->getDBorTables("TABLES");    
    }
        
    function 
listData($database, $table)
    {
        
// Returns data field names and their values
        
        
$sql "USE $database";
        
        
$this->mysqli->query($sql);
        
        
// Get field names first
        
$sql "SELECT * FROM $table";
        
        if (
$result $this->mysqli->query($sql)) 
        {
            
$titles $result->fetch_fields(); 
        }
        
        foreach(
$titles as $columnHead)
        {
            
$data['titles'][] = $columnHead->name;
        }
        
        
// Get data
        
while ($row $result->fetch_row()) 
        {
            
$data['rows'][] = $row;
        }
        
        return 
$data;
    }
}

?>