WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Poker Tournaments Poker Tournaments
Poker Guide for Developers Poker Guide for Developers
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
Internet Security Software
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
פרייסז - הכח לקנות עובר לידיים שלך
Texas Holdem Poker Evangelists

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : MySQL wrapper class (PHP 5+ only)
Categories : MySQL, Databases, Classes and Objects, Object Oriented Click here to Update Your Picture
Nicolas Connault
Date : Nov 29th 2004
Grade : 1 of 5 (graded 4 times)
Viewed : 32513
File : 4041.php
Images : No Images for this code example.
Search : More code by Nicolas Connault
Action : Grade This Code Example
Tools : My Examples List

Submit your own code examples  Submit your own code examples 
 

This class is for PHP 5+ only, and uses mysqli functions

<?php
/**
* Contains the MySQL class
* @package classes
*
*/

/**
* A wrapper for all functions necessary to access a MySQL database and manipulate the results.
*
* @package classes
* @author Nicolas Connault
*/
class MySQL
{
        var
$host ;
        var
$database;
        var
$user ;
        var
$pass ;
       
/**
        * @var string link_id    Points to the selected Database Connection.
        */
       
var $link_id;
       
/**
        * @var string    Result  Points to the last Query's Result (not an array)
        */
       
var $Result;
       
/**
        * @var  array Record Contains 1 row from the last Query's Result
        */
       
var $Record = array();
       
/**
        * @var  array data_array Contains ALL rows from the last Query's Result
        */
       
var $data_array = array();
       
/**
        * @var int  row Keeps track of the current row being pointed to by $this->Result
        */
       
var $row;
       
/**
        * @var string query  The last Query called
        */
       
var $query;
               

       
/**
        * Constructor function
        * Connects to our Database using our username and password (not very secure) and selects the appropriate Database
        *
        * @return Boolean True
        */
       
function __construct()
        {
           
$this->host = '127.0.0.1';
           
$this->user = 'root';
           
$this->pass = '';
           
$this->database = 'db';
           
$this->link_id = mysqli_connect($host,$user ,$pass) or $this->Error(mysqli_error());
           
$DB = mysqli_select_db($this->link_id,'sweetpeadesigns_com_au_-_pos') or $this->Error(mysqli_error());
            return
true;
        }

       
/**
        * Performs an SQL query $sql and saves the result identifier as $this->Result
        * If the SQL query isn't valid, the function Error() is called, which displays the error message and code
        * @param string $sql SQL query
        * @param string $location Location from which this query is being called.
        * @return string Result identifier
        */
       
function Query($sql$file, $line, $location)
        {
           
$this->Result = mysqli_query($this->link_id,$sql) or $this->Error(mysqli_error($this->link_id), $location, $file, $line, $sql);
           
$this->query = $sql;
           
# DEBUG   print $sql;
           
return $this->Result;
        }

       
/**
        * Fetches the current $row from the current $Result as an associative array $this->Record.
        * This is an associative array, it has no number indices. If you want number indices, use FetchRow() instead.
        * @return array Current Row
        */
       
function FetchArray()
        {
               
$this->Record = mysqli_fetch_array($this->Result, MYSQLI_ASSOC);
               
//$this->Clean();
               
return $this->Record;
        }

       
/**
        * Fetches the current $row from the current $Result as a numerical array $this->Record.
        *  This is a numerical array, it has no associative indices. If you want associative indices, use FetchArray() instead.
        * @return array Current Row
        */
       
function FetchRow()
        {
               
$this->Record = mysqli_fetch_row($this->Result);
                return
$this->Record;
        }

       
/**
        * Moves the Result pointer forward or backward (changes the var $row )
        * @param string $type Type of array ("assoc" or "num")
        * @param string $order Direction of navigation ("asc" or "desc")
        * @return array Current Row
        */
       
function navigateRow($type = "assoc", $order = "asc")
        {
                if (
$order == "asc")
                {
                        if (
mysqli_data_seek($this->Result, $this->row + 1))
                        {
                               
$this->row += 1;
                                if (
$type == "assoc")
                                {
                                       
$this->Record = mysqli_fetch_assoc($this->Result);
                                }
                                elseif (
$type == "num")
                                {
                                       
$this->Record = mysqli_fetch_row($this->Result);
                                }
                                else
                                {
                                        print
'<p>Error: the function nextRow($type) in the mySQL class takes one argument, either "assoc" or "num".</p>';
                                }
                        }
                        else
                        {
                                print
'<p>Error: You have reached the last row of the last query (' . $this->query . '). I now reset the result pointer to the first row</p>';
                               
mysqli_data_seek($this->Result, 0);
                        }
                }
                elseif (
$order == "desc")
                {
                        if (
mysqli_data_seek($this->Result, $this->row - 1))
                        {
                               
$this->row -= 1;
                                if (
$type == "assoc")
                                {
                                       
$this->Record = mysqli_fetch_assoc($this->Result);
                                }
                                elseif (
$type == "num")
                                {
                                       
$this->Record = mysqli_fetch_row($this->Result);
                                }
                                else
                                {
                                        print
'<p>Error: the function nextRow($type) in the mySQL class takes two arguments, type as either "assoc" or "num", and order as either "asc" or "desc".</p>';
                                }
                        }
                        else
                        {
                                print
'<p>Error: You have reached the first row of the last query (' . $this->query . '). I now reset the result pointer to the last row</p>';
                               
mysqli_data_seek($this->Result, mysqli_num_rows($this->Result) - 1);
                        }
                }
                return
$this->Record;
        }
       
         
/**
        *  "Cleans" the current row ($Record array) by stripping slashes from it
        *  You would use this when a string might have been saved with slashes to escape special characters
        * @return array Current Row
       
        function Clean()
        {
                foreach(@$this->Record as $Key => $Val)
                {
                        $this->Record[$Key] = stripslashes($Val);
                }
                return $this->Record;
        }
*/
        /**
        * Fills $data_array with every row of the last Query
        * This function is helpful if you want to store the entire result of a SELECT query without having to loop through each row separately.
        * @return array Entire result of Query
        */
       
function fill_Array()
        {
                               
                for(
$i = 0; $i < $this->TotalRows(); $i++)
                {
                       
mysqli_data_seek($this->Result, $i);
                       
$temp_array[] = mysqli_fetch_row($this->Result) or die("fill_array Query failed: " . mysqli_error($this->link_id));
                }
                if(isset(
$temp_array[0]))
                {
                    foreach (
$temp_array as $k => $v)
                    {
                            foreach (
$v as $k2 => $v2)
                            {
                                   
$this->data_array[] = $v2;
                            }
                    }
                    return
$this->data_array;
                }
        }

        function
TotalRows()
        {
               
$this->Rows = mysqli_num_rows($this->Result);
                return
$this->Rows;
        }

       
/**
        * Print the provided $record in a formatted HTML table.
        * The $record can be any array, but mostly a result of an SQL query.
        *                     E.g: $this->Record or $this->data_array
        * @param array $record Any array
        */
       
function Print_Result($record)
        {
                print
"<center><table border=\"1\" bgcolor=\"#F9FABC\" name=\"results\">\n<tr>\n";

                foreach(
$record as $k => $v)
                {
                        print
"\t<th bgcolor=\"#A9D5E2\">" . $k . "</th>\n"; //Prints each Column's title
               
}
                print
"\t</tr>\n<tr>";
               
                foreach(
$record as $k => $v)
                {
                        print
"\t<td>" . $v . "</td>\n";
                }
                print
"</tr>\n</table></center>\n\n";
        }

       
/**
        *  Closes the MySQL connection
        * The $record can be any array, but mostly a result of an SQL query. E.g: $this->Record or $this->data_array
        * @return boolean True if successful
        */
       
function Close()
        {
               
mysqli_close($this->link_id);
                return
true;
        }

       
/**
        * Displays the provided $Text as a MySQL Query error message
        * The text will be a generic mysqli_error() message with the location from which the query was called.
        * @param string $Text  MySQL Error Message
        * @param string $location The location from which the query was called
        */
       
function Error($Text, $location = "not given", $file = "unknown file", $line = "unknown line", $sql)
        {
                echo
'<div align="left">';
                echo
"<em>MySQL Error!</em>
                    <ul>
                        <li><em>File</em>:
$file</li>
                        <li><em>Line</em>:
$line</li>
                        <li><em>Section</em>:
$location</li>
                    </ul>"
;
                echo
'<hr width="40%">';
                echo
$Text;
                echo
"<p>$sql</p>";
                echo
'</div>';
                exit();
        }

       
/**
        * Unsets all unnecessary variables related to the MySQL functions
        */
       
function removeMysqlVars()
        {
            unset (
$this->link_id);
            unset (
$this->Result);
            unset (
$this->Record);
            unset (
$this->data_array);
            unset (
$this->row);
            unset (
$this->query);       
        }
       
        function
getInfo($result)
        {
            return
mysqli_info($result) ;
        }
}
?>


Usage Example
<?php
$myDB
= new MySQL();

$query = "SELECT * FROM users WHERE ID > 12";

// The fourth argument in the query function is for when you call this
// function within another function or method (eg. search::get_user)

$myDB->Query($query,__FILE__,__LINE__,'');

for(
$i = 0; $i < $myDB->TotalRows(); $i ++)
{
     
$array = $myDB->FetchArray();
     
$record[$i]['field1'] = $array['field1'];
     
$record[$i]['field2'] = $array['field2'];
}
?>



MySQL Handler
Categories : PHP, Databases, MySQL, Classes and Objects, PHP Classes
bookmarker - PHP, PHPLIB, MySQL WWW based bookmark manager
Categories : MySQL, PHP, MySQL, Complete Programs, Databases
This program allows you to upload an ODBC ressource - i.e. an MS-Access database to a MySQL server.
Categories : Databases, MySQL, Complete Programs, PHP, Databases
Online Automatic Class Generator for MySQL Tables
Categories : PHP, PHP Classes, Classes and Objects, Databases, MySQL
A template script to provide the ability to get the next or previous n records from a MySQL database.
Categories : Databases, PHP, MySQL
Powerful php/mysql Pagination for up to 6 URL Params
Categories : PHP, PHP Classes, Databases, MySQL, Navigation
Invision Forums Latest Threads list
Categories : PHP, Miscellaneous, Databases, MySQL
MySQL Query Caching
Categories : MySQL, Cache, Databases
email new items in db
Categories : PHP, Email, Databases, MySQL, Beginner Guides
mediaCat-GTK v2.0.0 - an mp3/cd/dvd cataloging utility written in php-gtk which interfaces with mysql and ms access (or db supported by PHP's Unified ODBC Functions)
Categories : PHP, MySQL, MS Access, Utilities, Databases
Mssql database Manager
Categories : PHP, Databases, MS SQL Server, Classes and Objects, PHP Classes
mod_auth_mysql - mod_auth_mysql was written in order to allow users to use the blazing quick speed of MySQL in order to store authentication information for their apache web servers.
Categories : Authentication, MySQL, Databases
BBS system for easy customization. Utilizes mySQL.
Categories : Complete Programs, MySQL, PHP, Databases
color codes for positive and negative numbers
Categories : PHP, MySQL, Databases, HTML
php-gtk mysql querying tool
Categories : PHP-GTK, MySQL, PHP, Databases