NamePros
Welcome, Guest! Ready to make a name for yourself in the domain business? We welcome both the hobbyist and professional domainer to join the discussion as part of the NamePros community.

Click here to create your profile to start earning reputation for posting, and trader ratings for buying & selling in our free e-marketplace. Build your trader rating with each successful sale. Our system has tracked over 100,000 sales and counting!
FAQ & TOS Register Search Today's Posts Mark Forums Read

Go Back   NamePros.com > Website Development Discussion Forums > Programming > CODE
Reload this Page PHP MySQL database wrapper class

CODE This forum is for posting code snippets and example scripts that aren't quite tutorials, but could be useful for others. You may post code snippets and/or completed scripts that you've written and want to share here.

Advanced Search
6 members in live chat ~  


Closed Thread
 
LinkBack Thread Tools
Old 09-20-2005, 04:21 PM THREAD STARTER               #1 (permalink)
Account Suspended
 
axilant's Avatar
Join Date: May 2004
Location: /etc/passwd
Posts: 2,178
axilant is a splendid one to beholdaxilant is a splendid one to beholdaxilant is a splendid one to beholdaxilant is a splendid one to beholdaxilant is a splendid one to beholdaxilant is a splendid one to behold
 

Member of the Month
July 2005

PHP MySQL database wrapper class


PHP Code:
<?PHP
/*
$hostname = "localhost";
$database = "db";
$username = "root";
$password = "";
$db = new db("$hostname:$database:$username:$password");
*/
class db
{
    var 
$_version "1.4";
    var 
$_lastupdate "9/20/2005";
    var 
$_author "Cody Selzer <axilant@gmail.com>";
    function 
db($args)
    {
        
$arg explode(":"$args);
        
$this->host $arg[0];
        
$this->database $arg[1];
        
$this->username $arg[2];
        
$this->password $arg[3];
        
$this->connect();
        
$this->select_db();
        
$this->close();
    }

    function 
connect() 
    {
        
$this->connect = @mysql_connect("$this->host""$this->username""$this->password");
        if(!
$this->connect)
        {
            
$this->error("Mysql Connection Error","Failed connecting to database server\r\n\r\n" mysql_error() . "");
        }
        return 
$this->connect;
    }

    function 
select_db() 
    {
        
$this->select_db = @mysql_select_db($this->database$this->connect);
        if(!
$this->select_db
        {
            
$this->error("Mysql Connection Error","Failed selecting to database\r\n\r\n" mysql_error() . "");
        }
        return 
$this->select_db;
    }
    function 
query($query
    {
        
$this->result mysql_query($query);
        if(!
$this->result
        {
            
$this->error("Mysql Query Error","Error Message: Failed executing database query\r\nDate/Time: " date('Y-m-d H:i:s') . "\r\nQuery: $query\r\nMySQL Error: " mysql_error() . "");
        }

        
$detect1 preg_replace('/DELETE/siU'1$query);
        
$detect2 preg_replace('/UPDATE/siU'1$query);
        
$detect3 preg_replace('/INSERT/siU'1$query);

        if(
$detect1 == || $detect2 == || $detect2 == 1
        {
            
$this->affected_rows mysql_affected_rows();
            
$this->affected_rows_total += $this->affected_rows;
        }

        
$this->counter++;
        return 
$this->result;
    }

    function 
fetch_row($query
    {
        
$this->result mysql_query($query);
        
$this->row $this->fetch_array($this->result);
        
$this->counter++;
        return 
$this->row;
    }

    function 
fetch_array($query
    {
        
$this->row = @mysql_fetch_array($query);
????: NamePros.com http://www.namepros.com/code/125354-php-mysql-database-wrapper-class.html
        return 
$this->row;
    }

    function 
num_rows($query
    {
        
$this->result mysql_query($query);
        
$this->num_rows mysql_num_rows($this->result);
        
$this->counter++;
        return 
$this->num_rows;
    }
    function 
count_queries() 
    {
        return 
$this->counter;
    }

    function 
affected_rows() 
    {
        if(
$this->affected_rows_total == '0'
        {
            
$this->affected_rows_total '0';
        }    
        return 
$this->affected_rows_total
    }
    function 
list_dbs()
    {
        return 
mysql_list_dbs();
    }
    function 
tablename($query)
    {
        return 
mysql_tablename($query$this->connect);
    }
    function 
num_fields($query)
    {
        return 
mysql_num_fields($query);
    }
    function 
error($title,$msg)
    {
       
$page "<html>\n\<head>\n\t<title>$title</title>\n</head>\n<body>\n\t<p>$msg</p>\n</body>\n</html>";
       print 
$page;
    }
    function 
list_tables()
    {
        
$sql $this->query("SHOW TABLES FROM $this->database");
        while(
$row $this->fetch_array($sql))
        {
            
$tables[] = $row[0];
        }
        return 
$tables;
    }

    function 
close() 
    {
        
register_shutdown_function('mysql_close');
    }
    function 
escape($arr)
    {
        if(
is_array($arr))
        {
            foreach(
$arr as $k => $v)
            {
                if (
is_array($v))
                {
                    
$this->escape($arr[$k]);
                }
                else
                {
                    if (
function_exists('get_magic_quotes'))
                    {
                        if(!
get_magic_quotes_gpc())
                        {
                            
$arr[$k] = stripslashes($v);
                        }
                    }
                    if(
function_exists('mysql_real_escape_string'))
                    {
                        
$arr[$k] = mysql_real_escape_string($v);
                    }
                    else
                    {
                        
$arr[$k] = addslashes($v); //real escape function doesnt exist, just readd the slashes.
                    
}
                }
               }
        }
        else
        {
            if (
function_exists('get_magic_quotes'))
            {
                if(!
get_magic_quotes_gpc())
                {
                    
$arr stripslashes($arr);
                }
                }
                if(
function_exists('mysql_real_escape_string'))
                {
                    
$arr mysql_real_escape_string($v);
                }
                else
                {
                        
$arr addslashes($arr);
                }
                return 
$arr;
        }
    }
    function 
clean_html($arr)
    {
        if(
is_array($arr))
        {
            foreach(
$arr AS $ar)
            {
                
$this->clean_html($ar);
            }
        }
        else
        {
            return(
htmlentities($arr));
        }
    }
    function 
clean($arr '')
    {
        if(
is_array($arr))
        {
            
//clean an array that is specified
            
$this->clean_html($arr);
            
$this->escape($arr);
        }
        else
        {
            
$types = array('_POST','_GET','_COOKIE','_SERVER','_SESSION');
            foreach(
$types AS $type)
            {
                
$this->clean_html($$type);
                
$this->escape($$type);
            }
        }
    }
    function 
sql_strip_ticks($data)
    {
        return 
str_replace("`"""$data);
    }
    function 
get_result_fields($query_id="") {
    
           if (
$query_id == "")
           {
            
$query_id $this->query_id;
        }
    
        while (
$field mysql_fetch_field($query_id))
        {
            
$Fields[] = $field;
        }        
        return 
$Fields;
       }
       function 
unescape($arr)
       {
       if(
is_array($arr))
        {
            foreach(
$arr as $k => $v)
            {
                if (
is_array($v))
                {
                    
$this->escape($arr[$k]);
                }
                else
                {
                    
$arr[$k] = stripslashes($v);
                }
               }
               return 
$arr;
        }
        else
        {        
            
$arr stripslashes($arr);
            return 
$arr;
        }
       }
    
//based off of ipb 1.3's code//basicly there code... but a few things changed.
    
function get_table_sql($tbl$create_tbl)
    {        
        if(
$create_tbl)
        {
            print 
"DROP TABLE IF EXISTS `$tbl`;";
                
$ctable $this->fetch_row("SHOW CREATE TABLE $tbl");
                print 
$this->sql_strip_ticks($ctable['Create Table']).";\n";
        }
        
$sql $this->query("SELECT * FROM $tbl");
        
$row_count $this->num_rows("SELECT * FROM $tbl");        
        if (
$row_count 1)
        {
            return 
true;
        }
        
//---------------------------
        // Get col names
        //---------------------------
        
        
$f_list "";
    
        
$fields $this->get_result_fields($sql);
        
        
$cnt count($fields);
        
        for( 
$i 0$i $cnt$i++ )
        {
            
$f_list .= $fields[$i]->name ", ";
        }
        
        
$f_list preg_replace"/, $/"""$f_list );
        
        while (
$row $this->fetch_array($sql))
        {
            
//---------------------------
            // Get col data
            //---------------------------
            
            
$d_list "";
            
            for( 
$i 0$i $cnt$i++ )
            {
                if ( ! isset(
$row$fields[$i]->name ]) )
                {
                    
$d_list .= "NULL,";
                }
                elseif ( 
$row$fields[$i]->name ] != '' )
                {
                    
$d_list .= "'".$this->escape($row$fields[$i]->name ]). "',";
                }
                else
                {
                    
$d_list .= "'',";
                }
            }
            
            
$d_list preg_replace"/,$/"""$d_list );
            
            print(
"INSERT INTO $tbl ($f_list) VALUES($d_list);\n");
        }
        
        return 
TRUE;
        
    }
    function 
doact($step '',$table)
    {
        switch(
$step)
        {
            case 
"0":
            
$query "ANALYZE TABLE $table";
            break;
            case 
"1":
            
$query "REPAIR TABLE $table";
            break;
            default:
            
$query "OPTIMIZE TABLE $table";
            break;
        }
        return 
$this->query($query);
    }
    function 
optimize()
    {
        
$tables $this->list_tables();
        
        foreach(
$tables AS $table)
        {
            
$this->doact("0",$table);
            
$this->doact("1",$table);
            
$this->doact("",$table);
        }
        
    }
    function 
backups()
    {
        if (!
is_dir("./backups")) {
            @
mkdir("./backups/""0666");
        }
        
$d dir("./backups");
        
$i $BackupSize 0;
        
$opt "<select name=\"file\">\n<option>Select one...</option>";
        while (
false !== ($entry $d->read())) 
        {
            if (
$entry!="." and $entry!=".." and (ereg(".sql$",$entry)))
            {
                
$opt .= "<option>$entry</option>";
            }    
        }
        
$opt .= "</select>";
        return 
$opt;
    }
    function 
execute_file($file)
    {
        
$str file_get_contents($file);
          if(!
$str)
          {
             
$this->error("Error opening $file!","Unable to read the contents of $file.");
          }
      
        
$sql explode(';'$str);
        foreach (
$sql as $query
        {
            if (
$query!=""
????: NamePros.com http://www.namepros.com/showthread.php?t=125354
            {
                
$r $this->query($query);
            }
        }
   }
}
?>
Example Usage:

PHP Code:
$hostname "localhost";
$database "db";
$username "root";
$password "";
$db = new db("$hostname:$database:$username:$password");
$row $db->fetch_row("SELECT * FROM tablename");
print_r($row); 
Thats only basic usage.

Im planning on making an entire website dedicated to a mysql wrapper in the future.

TODO:
Save Database (backup...)
Fix a few things that i noticed...
Make a complete guide on how to use this.

Updated it, im finishing linkzor.com And I got done with database backup/restore. Added unescape() to remove slashes in an array and a non-array.

If anyone finds a bug, please let me know via pm.

Cody Selzer

Rep or np$ (maybe both?) donation would be great
Last edited by axilant; 09-22-2005 at 04:38 PM.
axilant is offline  
Old 09-22-2005, 04:53 AM   #2 (permalink)
Tech Support
Join Date: Mar 2005
Posts: 4,944
Eric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatness
 

Member of the Month
MOTM September 2005
Save a Life Child Abuse 9/11/01 :: Never Forget Baby Health Marrow Donor Program AIDS/HIV Breast Cancer Animal Rescue Cystic Fibrosis Ethan Allen Fund Animal Cruelty Ethan Allen Fund Ethan Allen Fund Baby Health Cancer Alzheimer's Protect Our Planet Cancer Survivorship SIDS Child Abuse Diabetes Protect Our Planet Multiple Sclerosis Autism Adoption Special Olympics
Thanks, I'll test this out in a script I'm currently working on.


-Eric
Eric is offline  
Closed Thread


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools


Similar Threads
Thread Thread Starter Forum Replies Last Post
Googlism - What does google think of you? deadserious The Break Room 55 12-15-2005 09:09 AM
Tutorial: How to Install Apache2 MySQL and PHP on Windows deadserious Webmaster Tutorials 35 09-21-2005 09:46 PM
HOW TO: Use shell to control MySQL. abdulmueid Webmaster Tutorials 16 08-27-2005 08:17 AM
Paypal Settlement CMachuca The Break Room 3 07-31-2004 10:14 PM
Paypal Settlement Lord The Break Room 2 07-30-2004 09:30 PM

 
All times are GMT -7. The time now is 02:13 PM.

Domain name forum recommended by Domaining.com Powered by: vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.6.0 Ad Management plugin by RedTyger