Go Back   vb.org Archive > vBulletin 3 Discussion > vB3 Programming Discussions
Prev Previous Post   Next Post Next
  #16  
Old 12-06-2005, 08:03 PM
Adrian Schneider's Avatar
Adrian Schneider Adrian Schneider is offline
 
Join Date: Jul 2004
Posts: 2,528
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Here is my DB class for one of my sites.

PHP Code:
<?php

class Database
{
    var 
$host;
    var 
$username;
    var 
$password;
    var 
$databasename;
    var 
$connection;
    
    
/**
     * Constructor Method
     * Initializes connection and selects database.
    **/
    
function Database($host$username$password$databasename)
    {
        
$this->host $host;
        
$this->username $username;
        
$this->password $password;
        
$this->databasename $databasename;

        
$this->connect($this->host$this->username$this->password);
    }
    
    
/**
     * Establishes MySQL connection.
    **/
    
function connect()
    {
        
$this->connection = @mysql_connect($this->host$this->username$this->password);
        if (!
$this->connection)
        {
            
$error = new Page;
            
$error->error('Could not establish database connection.</p><p>' mysql_error());
        }
        return 
$this->select_db($this->databasename);
    }
    
    
/**
     * Selects MySQL database.
    **/
    
function select_db()
    {
        
$resource = @mysql_select_db($this->databasename$this->connection);
        if (!
$resource)
        {
            
$error = new Page;
            
$error->error('Could not select database "' $this->databasename '".');
        }
        return 
$resource;
    }
    
    
/**
     * Executes a MySQL query.
    **/
    
function query($querystring)
    {
        if (
strpos($querystring"\t\t\t\t") !== false)
        {
            
$querystring str_replace("\t\t\t\t""\t\t"$querystring);
            
$querystring str_replace("\t\t\t""\t"$querystring);
        }
        
$resource mysql_query($querystring$this->connection);
        if (!
$resource)
        {
            
$this->debug_query($querystring);
        }
        return 
$resource;
    }
    
    
/**
     * Fetches rows from the database.
    **/
    
function fetch($result)
    {
        if (
mysql_num_rows($result))
        {
            
$resource mysql_fetch_assoc($result);
            return 
$resource;
        }
        return 
false;
    }
    
    
/**
     * Halts execution of the script and displays the problem.
    **/
    
function debug_query($query)
    {
        
$error = new Page;
        
$errormessage '<h2 class="queryfail">Failed Query:</h2><div style="background-color: #EEEEEE; width:640px; padding:5px; margin: 0 auto;">';
        
$errormessage .= '<pre class="query">' $this->highlight_sql($query) . '</pre></div>';
        if (
mysql_error())
        {
            
$errormessage .= '<h2 class="queryfailHeader">Reason:</h2>';
            
$errormessage .= '<p class="queryfailReason">' mysql_error() . '</p>';
        }

        
$error->error($errormessage'Database Error');
    }

    
/**
     * Highlights MySQL Code
    **/
    
function highlight_sql($query)
    {
        
$query preg_replace("/['\"]([^'\"]*)['\"]/i""'<span style='color: #FF6600'>$1</span>'"$query, -1);

        
$find = array(
            
'*',
            
'SELECT ',
            
'UPDATE ',
            
'DELETE ',
            
'INSERT ',
            
'CREATE ',
            
'TABLE ',
            
'INTO',
            
'VALUES',
            
'FROM',
            
'LEFT',
            
'JOIN',
            
'WHERE',
            
'LIMIT',
            
'ORDER BY',
            
'AND',
            
'OR ',
            
'DESC',
            
'ASC',
            
'ON ',
            
"\t\t\t",
            
'INT ',
            
'varchar ',
            
'VARCHAR ',
            
'NOT NULL',
            
'AUTO_INCREMENT',
            
'UNSIGNED',
            
'PRIMARY KEY '
        
);
        
        
$replace = array(
            
'<span style="#FF6600; font-weight: bold;">*</span>',
            
'<span style="color: #00AA00; font-weight: bold;">SELECT </span>',
            
'<span style="color: #00AA00; font-weight: bold;">UPDATE </span>',
            
'<span style="color: #00AA00; font-weight: bold;">DELETE </span>',
            
'<span style="color: #00AA00; font-weight: bold;">INSERT </span>',
            
'<span style="color: #00AA00; font-weight: bold;">CREATE </span>',
            
'<span style="color: #00AA00; font-weight: bold;">TABLE </span>',
            
'<span style="color: #00AA00; font-weight: bold;">INTO</span>',
            
'<span style="color: #00AA00; font-weight: bold;">VALUES</span>',
            
'<span style="color: #00AA00; font-weight: bold;">FROM</span>',
            
'<span style="color: #00CC00; font-weight: bold;">LEFT</span>',
            
'<span style="color: #00CC00; font-weight: bold;">JOIN</span>',
            
'<span style="color: #00AA00; font-weight: bold;">WHERE</span>',
            
'<span style="color: #AA0000; font-weight: bold;">LIMIT</span>',
            
'<span style="color: #00AA00; font-weight: bold;">ORDER BY</span>',
            
'<span style="color: #0000AA; font-weight: bold;">AND</span>',
            
'<span style="color: #0000AA; font-weight: bold;">OR </span>',
            
'<span style="color: #0000AA; font-weight: bold;">DESC</span>',
            
'<span style="color: #0000AA; font-weight: bold;">ASC</span>',
            
'<span style="color: #00DD00; font-weight: bold;">ON </span>',
            
"\t",
            
'<span style="color: #0000AA; font-weight: bold;">INT </span>',
            
'<span style="color: #0000AA; font-weight: bold;">varchar </span>',
            
'<span style="color: #0000AA; font-weight: bold;">VARCHAR </span>',
            
'<span style="color: #0000AA; font-weight: bold;">NOT NULL</span>',
            
'<span style="color: #0000AA; font-weight: bold;">AUTO_INCREMENT</span>',
            
'<span style="color: #0000AA; font-weight: bold;">UNSIGNED</span>',
            
'<span style="color: #0000AA; font-weight: bold;">PRIMARY KEY </span>',
        );
        return 
str_replace($find$replace$query);
    }
    
    
/**
     * Escapes data when going into the database.
     * This is not for SQL Injections.
    **/
    
function escape($value)
    {
        if (!
is_int($value))
        {
            if (
is_numeric($value))
            {
                
$value floatval($value);
            }
            else
            {
                
$value = (get_magic_quotes_gpc()) ? $value  addslashes($value);
            }
            
$value "'" $value "'";
        }
        return 
$value
    }
    
    
/**
     * Checks how many rows were found from a query.
    **/
    
function num_rows($resource)
    {
        return 
mysql_num_rows($resource);
    }
    
    
/**
     * Insert data into the database.
     * Generates query based on $data array (field => val)
    **/
    
function insert($table$data)
    {
        
// Field Names
        
$columnbit '';
        
$columns array_keys($data);
        for (
$i=0$i<count($columns); $i++)
        {
            
$columnbit .= (($i) ? ', ' '') . '`' $columns[$i] . '`';
        }

        
// Values
        
$valuebit '';
        
$values array_values($data);
        for (
$i=0$i<count($values); $i++)
        {
            
$value $this->escape($values[$i]);
        
            
$valuebit .= "\t\t\t\t" $value . (($i != count($values)-1) ? ', ' "\n" '');
        }
        
        
// Run Query
        
$this->query('
            INSERT INTO ' 
$table.  '
                (' 
$columnbit ')
            VALUES (' 
"\n" .  
                
$valuebit '
            )'
        
);
            
    }
    
    
/**
     * Update data in the database.
     * Generates query based on $data array (field => val)
    **/
    
function update($table$data$whereclause)
    {
        
$valuestofields '';
        
$i 0;
        foreach (
$data as $field => $value)
        {
            
$i++;
            
$valuestofields .= $field ' = ' $this->escape($value) . (($i != count($data)) ? ', ' '') . "\n\t\t\t\t";
        }
        
// Run Query
        
$this->query('
            UPDATE ' 
$table.  '
            SET' 
"\n\t\t\t\t" 
                
$valuestofields 
            
$whereclause
        
);
            
    }
    

}


?>
Does anyone know of a good SQL syntax highlighter (that doesn't require installing additional libraries)?

[edit]Usage being:
PHP Code:
$db = new Database('server''user''pass''db'); 
just replace the error handling method ... mine uses another class for displaying things.
Reply With Quote
 

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT. The time now is 05:50 AM.


Powered by vBulletin® Version 3.8.12 by vBS
Copyright ©2000 - 2025, vBulletin Solutions Inc.
X vBulletin 3.8.12 by vBS Debug Information
  • Page Generation 0.05473 seconds
  • Memory Usage 2,991KB
  • Queries Executed 12 (?)
More Information
Template Usage:
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_header_end
  • (1)ad_header_logo
  • (1)ad_navbar_below
  • (1)ad_showthread_beforeqr
  • (13)bbcode_php
  • (6)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)navbar
  • (3)navbar_link
  • (120)option
  • (17)post_thanks_box
  • (17)post_thanks_button
  • (1)post_thanks_javascript
  • (1)post_thanks_navbar_search
  • (17)post_thanks_postbit_info
  • (17)postbit
  • (13)postbit_onlinestatus
  • (17)postbit_wrapper
  • (1)showthread_list
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available:
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files:
  • ./showthread.php
  • ./global.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/class_hook.php
  • ./includes/modsystem_functions.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_threadedmode.php
  • ./includes/functions_post_thanks.php 

Hooks Called:
  • init_startup
  • init_startup_session_setup_start
  • init_startup_session_setup_complete
  • cache_permissions
  • fetch_postinfo_query
  • fetch_postinfo
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • style_fetch
  • cache_templates
  • global_start
  • parse_templates
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • forumjump
  • showthread_post_start
  • showthread_query_postids_threaded
  • showthread_threaded_construct_link
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • post_thanks_function_post_thanks_off_start
  • post_thanks_function_post_thanks_off_end
  • post_thanks_function_fetch_thanks_start
  • post_thanks_function_fetch_thanks_end
  • post_thanks_function_thanked_already_start
  • post_thanks_function_thanked_already_end
  • fetch_musername
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • post_thanks_function_can_thank_this_post_start
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • showthread_complete