frank
Goto Top

PHP DB-Klasse

Da ich mal wieder eine Anfrage für eine DB-Klasse per PN bekam, veröffentliche ich diese einfach mal.

Hier eine PHP DB-Klasse die UTF-8 Verbindungen aufbaut. Ursprünglich kommt sie aus einem "MYSQL-Buch" von Michael Kofler. Ich habe sie hier und da ein wenig angepasst. Verbesserungsvorschläge, Erweiterungen etc. sind natürlich willkommen. Die Klasse benutzt PHP5 und mysqli.

<?
/**
 * DB Class
 *
 * THIS DB Class USE UTF-8!
 * FOR ISO CONNECTION COMMENT THIS ROW: $utf = $this->queryExecute("SET NAMES 'utf8'"); OUT! 
 *
 * DB Connect :
 * $db = new MyDb("localhost","dbuser","dbpass","dbname"); 
 *
 * Examples:
 *
 * only one result:
 * ----------------
 * if (($n = $db->querySingleItem("SELECT COUNT(*) FROM titles"))!=-1) { 
 *    printf("<p>Anzahl der Titel: %d</p>",$nr); 
 * }
 *
 * more results:
 * -------------
 * if ($result=$db->queryObjectArray("SELECT * FROM titles")) { 
 *    foreach ($result as $row) {
 *        printf("<br />TitleID:%d Title=%s Subtitle=%s\",$row->titleID,$row->title,$row->subtitle); 
 *    }
 * }
 *
 * count a select with affectedRows:
 * ---------------
 * if ($nr=$db->queryExecute("SELECT * FROM titles")) { 
 *    printf("<p>Anzahl der Titel: %d</p>",$nr); 
 * }
 *
 * execute a sql without result (only true/false returns)
 * -------------------------------------------------------
 * if ($result=$db->execute("UPDATE titles SET titel='my new Titel'")) { 
 *  echo "successful"; 
 * }
 *
 * if you like to see the short statistic use:
 * $db->showStatistics();
 * in your programm.
 *
 */

class MyDb {
    protected $mysqli;
    protected $showerror = true;   // set FALSE if you don't want to see error messages 
    protected $showsql   = false;  // set TRUE if you want to see all SQL queries for debugging purposes
    protected $sqlcounter = 0;     // counter for SQL commands
    protected $rowcounter = 0;     // counter for returned SELECT rows
    protected $dbtime     = 0;     // counter for time needed to execute queries
    protected $starttime;

    // constructor
    function __construct($dbhost, $dbuser, $dbpass, $dbname) {
        $this->mysqli = @new mysqli($dbhost, $dbuser, $dbpass, $dbname);
        // test, connect ok?
        if(mysqli_connect_errno()) {
            $this->printerror("Sorry, no connection! (" . mysqli_connect_error() . ")");  
            // you might add output for HTML code to close the page
            // here (</body></html> etc.)
            $this->mysqli = FALSE;
            exit();
        }
        // SET DB INTO UTF8 MODE
        $utf = $this->queryExecute("SET NAMES 'utf8'");  
        $this->starttime = $this->microtime_float();
    }

    // destructor
    function __destruct() {
        $this->close();
    }

    // explicit close
    function close() {
        if($this->mysqli)
        $this->mysqli->close();
        $this->mysqli = FALSE;
    }

    function getMysqli() {
        return $this->mysqli;
    }

    // execute SELECT query, return array
    function queryObjectArray($sql) {
        $this->sqlcounter++;
        $this->printsql($sql);
        $time1  = $this->microtime_float();
        $result = $this->mysqli->query($sql);
        $time2  = $this->microtime_float();
        $this->dbtime += ($time2 - $time1);
        if($result) {
            if($result->num_rows) {
                while($row = $result->fetch_object())
                $result_array = $row;
                $this->rowcounter += sizeof($result_array);
                return $result_array; }
                else
                return FALSE;
        } else {
            $this->printerror($this->mysqli->error);
            return FALSE;
        }
    }

    // execute SELECT query, return array
    function queryArray($sql) {
        $this->sqlcounter++;
        $this->printsql($sql);
        $time1  = $this->microtime_float();
        $result = $this->mysqli->query($sql);
        $time2  = $this->microtime_float();
        $this->dbtime += ($time2 - $time1);
        if($result) {
            if($result->num_rows) {
                while($row = $result->fetch_array())
                $result_array = $row;
                $this->rowcounter += sizeof($result_array);
                return $result_array;
            }else {
                return FALSE;
            }
        } else {
            $this->printerror($this->mysqli->error);
            return FALSE;
        }
    }


    // execute a SELECT query which returns only a single
    // item (i.e. SELECT COUNT(*) FROM table); return
    // this item
    // beware: this method return -1 for errors (not 0)!
    function querySingleItem($sql) {
        $this->sqlcounter++;
        $this->printsql($sql);
        $time1  = $this->microtime_float();
        $result = $this->mysqli->query($sql);
        $time2  = $this->microtime_float();
        $this->dbtime += ($time2 - $time1);
        if($result) {
            if ($row=$result->fetch_array()) {
                $result->close();
                $this->rowcounter++;
                return $row;
            } else {
                // query returned no data
                return -1;
            }
        } else {
            $this->printerror($this->mysqli->error);
            return -1;
        }
    }

    // execute a SQL command with the number of affected rows as results (no query)
    function queryExecute($sql) {
        $this->sqlcounter++;
        $this->printsql($sql);
        $time1  = $this->microtime_float();
        $result = $this->mysqli->real_query($sql);
        $time2  = $this->microtime_float();
        $this->dbtime += ($time2 - $time1);
        if($result) {
            // return TRUE;
            return $this->mysqli->affected_rows;
        } else {
            $this->printerror($this->mysqli->error);
            return FALSE;
        }
    }

    // execute a SQL command without results, only true/false (no query)
    function execute($sql) {
        $this->sqlcounter++;
        $this->printsql($sql);
        $time1  = $this->microtime_float();
        $result = $this->mysqli->real_query($sql);
        $time2  = $this->microtime_float();
        $this->dbtime += ($time2 - $time1);
        if($result) {
            return TRUE;
        } else {
            $this->printerror($this->mysqli->error);
            return FALSE;
        }
    }


    // get insert_id after an INSERT command
    function insertId() {
        return $this->mysqli->insert_id;
    }

    // get the number of affected rows after query command
    function affectedRows() {
        return $this->mysqli->affected_rows;
    }

    // get mysql system status
    function mysqlStats() {
        return $this->mysqli->stat();
    }

    // insert \ before ', " etc. 
    function escape($txt) {
        return trim($this->mysqli->escape_string($txt));
    }

    // return 'NULL' or '<quoted string>' 
    function sql_string($txt) {
        if(!$txt || trim($txt)=="")  
        return 'NULL';  
        else
        return "'" . $this->escape(trim($txt)) . "'";  
    }

    function error() {
        return $this->mysqli->error;
    }

    private function printsql($sql) {
        if($this->showsql)
        printf("<p><font color=\"#0000ff\">%s</font></p>\n",  
        htmlspecialchars($sql));
    }

    private function printerror($txt) {
        if($this->showerror)
        printf("<p><font color=\"#ff0000\">%s</font></p>\n",  
        htmlspecialchars($txt));
    }

    function showStatistics() {
        $totalTime = $this->microtime_float() - $this->starttime;
        printf("<p><font color=\"#0000ff\">SQL commands: %d\n",  
        $this->sqlcounter);
        printf("<br />Sum of returned rows: %d\n",  
        $this->rowcounter);
        printf("<br />Sum of query time (MySQL): %f\n",  
        $this->dbtime);
        printf("<br />Processing time (PHP): %f\n",  
        $totalTime - $this->dbtime);
        printf("<br />Total time since MyDB creation / last reset: %f</font></p>\n",  
        $totalTime);
    }

    function resetStatistics() {
        $this->sqlcounter = 0;
        $this->rowcounter = 0;
        $this->dbtime     = 0;
        $this->starttime = $this->microtime_float();  }

        private function microtime_float() {
            list($usec, $sec) = explode(" ", microtime());  
            return ((float)$usec + (float)$sec);
        }

}
?>

Viel Spaß damit face-smile

Gruß
Frank

Content-ID: 117046

Url: https://administrator.de/tutorial/php-db-klasse-117046.html

Ausgedruckt am: 24.12.2024 um 13:12 Uhr

nxclass
nxclass 28.05.2009 um 16:53:09 Uhr
Goto Top
bissel 'Fett' die Klasse - wer will von jeder SQL Anweisung die Zeiten wissen ?

... wieso nicht mit PDO ?

Edit:
Und bitte die 'PHP Documentor' Tags nicht vergessen face-wink
masterG
masterG 02.06.2009 um 18:29:11 Uhr
Goto Top
ich hab da auch noch eine:

<?php

class mysql
{
	protected $sql_link;
	protected $last_result;
	protected $num_querys = 0;
	protected $last_sql = '';  
	protected $sql_array = array();
	protected $sql_false = 0;
	protected $sql_true = 0;
	protected $query_time = 0;
	
	public function __construct($config)
	{
		$host = $config['db']['host'];  
		$user = $config['db']['username'];  
		$pass = $config['db']['password'];  
		$db	  = $config['db']['database'];  
		
		if( !( $this->sql_link = mysql_connect($host, $user, $pass) ) )
		{
			$this->error();
		}
		
		if( !mysql_select_db($db, $this->sql_link) )
		{
			$this->error();
		}
		
		return true;
	}
	
	public function doQuery($sql, $unbuffer = false)
	{
		$this->num_querys++;
		$this->last_sql = $sql;
		$this->sql_array = $sql;
		
		$start = microtime(true);
		
		if( $unbuffer == true )
		{
			if( $result = mysql_unbuffered_query($sql, $this->sql_link) )
			{
				$this->last_result = $result;
				$this->sql_true++;
			}
			else
			{
				$this->error();
				$this->sql_false++;
				$result = false;
			}
		}
		else
		{
			if( $result = mysql_query($sql, $this->sql_link) )
			{
				$this->last_result = $result;
				$this->sql_true++;
			}
			else
			{
				$this->error();
				$this->sql_false++;
				$result = false;
			}
		}
		
		$this->query_time += microtime(true) - $start;
		
		return $result;
	}
	
	public function fetchrow($result = '')  
	{
		if(	empty($result) )
		{
			$result = $this->last_result;
		}
		
		return mysql_fetch_assoc($result);
	}
	
	public function getOne($sql)
	{
		return $this->fetchrow($this->doQuery($sql));
	}
	
	public function getAll($sql)
	{
		$res 	= $this->doQuery($sql);
		$result = array();
		
		while($data = $this->fetchrow($res))
		{
			$result = $data;
		}
		
		return $result;
	}
	
	public function lastId()
	{
		return mysql_insert_id($this->sql_link);	
	}
	
	public function escape($var)
	{
		return '\''. mysql_real_escape_string($var, $this->sql_link) . '\'';  
	}
	
	public function get_debug_infos($strict = false)
	{
		$debug = array();
		$debug['q_time'] = $this->query_time;  
		$debug['q_count'] = $this->num_querys;  
		$debug['q_true'] = $this->sql_true;  
		$debug['q_false'] = $this->sql_false;  
		$debug['q_all'] = $this->sql_array;  
		
		return $debug;
	}
	
	protected function error()
	{
		trigger_error('[DB Error] <b>Fehler bei der Abfrage von Daten aus der Datenbank</b>: <pre>'. $this->last_sql .'</pre> Fehler: '. mysql_error($this->sql_link) .'::'.mysql_errno($this->sql_link), E_USER_NOTICE);  
	}
	
	public function __destruct()
	{
		return mysql_close($this->sql_link);
	}
	
}
?>

aber PDO ist natürlich besser. Das ist eine alte Klasse die ich mal geschrieben habe. Mittlerweile schreib ich datenbank klassen nur mit PDO
masterG
masterG 22.10.2011 um 09:59:30 Uhr
Goto Top
Nach langer Zeit hab ich mal wieder ein bisschen herumgebastelt. Um genau zu sein die gesammte Klasse über den Haufen geworfen und neu programmiert.
Das Ergebnis sieht man auf Github: http://github.com/gianluca311/phpMySQLiDatabase-class