Source for file db_sqlite.class.php
Documentation is available at db_sqlite.class.php
* Database Class provides an API to communicate with SQLite Database.
* Nearly all methods are identical to my other Oracle and MySQL classes.
* This is the PHP 5 only class, the old PHP 4 class won't be extended anymore!
* Requires dbdefs.inc.php for global access data (dbname,appname).
* @author Sascha 'SieGeL' Pfalz <php@saschapfalz.de>
* @version 0.20 (07-Aug-2010)
* $Id: db_sqlite.class.php,v 1.2 2010/08/07 17:47:03 siegel Exp $
* @license http://opensource.org/licenses/bsd-license.php BSD License
private $classversion =
'0.20';
* Internal connection handle.
* The default database filename permission mode.
* The Name of the application using this class.
* Contains the actual query to be processed.
* Flag indicates how the class should interact with errors
protected $showError =
db_SQLite::DBOF_SHOW_NO_ERRORS;
* Debugstate, default is OFF.
protected $debug =
db_SQLite::DBOF_DEBUGOFF;
* The SAPI type of php (used to detect CLI sapi)
* Email Address for the administrator of this project
private $AdminEmail =
'';
* Error code of last sqlite operation (set in Print_Error()).
* Error string of last sqlite operation (set in Print_Error()).
* Set to TRUE if Connect() should use persistant connection, else new one (Default)
private $usePConnect =
FALSE;
* How many queries where executed.
private $querycounter =
0;
* Amount of time spent executing class methods.
private $querytime =
0.000;
/** DEBUG: No Debug Info */
/** DEBUG: Debug to screen */
const DBOF_DEBUGSCREEN =
2;
/** DEBUG: Debug to error.log */
const DBOF_DEBUGFILE =
4;
* Connect and error handling.
* If NO_ERRORS is set and an error occures, the class still reports an
* an error of course but the error shown is reduced to avoid showing
* sensible informations in a productive environment.
* Set RETURN_ALL_ERRORS if you want to handle errors yourself.
const DBOF_SHOW_NO_ERRORS =
0;
const DBOF_SHOW_ALL_ERRORS =
1;
const DBOF_RETURN_ALL_ERRORS =
2;
* All defines for custom error codes *
const SQLITEDB_ERR_NO_APPNAME_DEFINE = -
1;
const SQLITEDB_ERR_NO_CONNECTION = -
2;
const SQLITEDB_ERR_NO_ACTIVE_CONNECT = -
3;
const SQLITEDB_ERR_SQL_SYNTAX_ERROR = -
4;
const SQLITEDB_ERR_EXTENSION_MISSING = -
5;
* @param string $ext_config Pass here the full name to your define file where all external class defines are set. If empty uses "dbdefs.inc.php".
$this->AdminEmail = isset
($_SERVER['SERVER_ADMIN']) ?
strip_tags($_SERVER['SERVER_ADMIN']) :
'';
require_once('dbdefs.inc.php');
require_once($ext_config);
$this->setErrorHandling(db_SQLite::DBOF_SHOW_ALL_ERRORS);
$this->myErrStr =
'Missing function sqlite_open() - extension not loaded!';
$this->myErrno =
db_SQLite::SQLITEDB_ERR_EXTENSION_MISSING;
if(defined('SQLITEDB_APPNAME')==
false)
$this->myErrno =
db_SQLite::SQLITEDB_ERR_NO_APPNAME_DEFINE;
$this->myErrStr =
'Define SQLITEDB_APPNAME not set!';
$this->appname =
'!!! NOT SET !!!';
$this->setErrorHandling(db_SQLite::DBOF_SHOW_ALL_ERRORS);
$this->Print_Error('dbdefs.inc.php not found/wrong configured! Please check Class installation!');
if(defined('SQLITEDB_ERRORMODE')) // You can set a default behavour for error handling in debdefs.inc.php
* Performs the connection to a SQLite database file.
* If anything goes wrong calls Print_Error().
* You should set the defaults for your connection by setting
* database filename in dbdefs.inc.php and leave connect() parameters empty.
* @param string $database Optional Filename of database to use
* @param string $mode Optional the file protection bits as octal number, defaults to 0666.
* @return mixed Either the DB connection handle or NULL in case of an error.
public function Connect($database =
'', $mode =
0)
if($this->usePConnect ==
FALSE)
$this->myErrno =
db_SQLite::SQLITEDB_ERR_NO_CONNECTION;
* Disconnects from SQLite database.
* You may optionally pass an external link identifier.
* @param mixed $other_sock Optionally your own connection handle to close, else internal will be used
* Single-Row query method.
* Returns only the first row of a given query!
* Resflag can be one of SQLITE_NUM or SQLITE_ASSOC or SQLITE_BOTH depending on what kind of array you want to be returned.
* @param string $querystring The query to be executed.
* @param integer $resflag Decides how the result should be returned:
* - SQLITE_ASSOC = Data is returned as associative array (default value).
* - SQLITE_NUM = Data is returned as numbered array.
* - SQLITE_BOTH = Data is returned both as numbered and as associative array.
* @param integer $no_exit Decides how the class should react on errors.
* If you set this to 1 the class won't automatically exit on an error but instead return the sqlite_errno value.
* Default of 0 means that the class calls Print_Error() and exists.
* @return mixed Either the result of the query or an error code or no return value at all
* @see sqlite_unbuffered_query()
* @see sqlite_fetch_array()
public function Query($querystring,$resflag =
SQLITE_ASSOC, $no_exit =
0)
$this->myErrno =
db_SQLite::SQLITEDB_ERR_NO_ACTIVE_CONNECT;
return($this->Print_Error('Query(): No active connection!',$querystring));
$no_exit =
1; // Override if user has set master define
$this->myErrno =
db_SQLite::SQLITEDB_ERR_SQL_SYNTAX_ERROR;
* Performs a multi-row query and returns result identifier.
* @param string $querystring The Query to be executed
* @param integer $no_exit The error indicator flag, can be one of:
* - 0 = (Default), In case of an error Print_Error is called and script terminates
* - 1 = In case of an error this function returns the error from sqlite_last_error()
* @return mixed A resource identifier or an errorcode (if $no_exit = 1)
public function QueryResult($querystring, $no_exit =
0)
$this->myErrno =
db_SQLite::SQLITEDB_ERR_NO_ACTIVE_CONNECT;
return($this->Print_Error('QueryResult(): No active Connection!',$querystring));
$this->myErrno =
db_SQLite::SQLITEDB_ERR_SQL_SYNTAX_ERROR;
* Fetches next row from result handle.
* Returns either numeric array (SQL_NUM), associative array (SQL_ASSOC) or both (SQLITE_BOTH) for one data row as pointed to by result var.
* @param mixed $result The resource identifier as returned by QueryResult()
* @param integer $resflag How you want the data to be returned:
* - SQLITE_ASSOC = Data is returned as associative array.
* - SQLITE_NUM = Data is returned as numbered array.
* - SQLITE_BOTH = Data is returned both as associative and numbered array.
* @return array One row of the resulting query or NULL if there is no data anymore to read.
* @see sqlite_fetch_array()
public function FetchResult($result,$resflag =
SQLITE_ASSOC)
return($this->Print_Error('FetchResult(): No valid result handle!'));
* Frees result returned by QueryResult().
* Note that SQLite has nothing to free (?) so here only the internal query variable is set to an empty string.
* @param mixed $result The resource identifier you want to be freed.
* Returns number of rows affected by most recent DML operation against $dbhandle.
* @param resource $sock Optional a connection handle, if none given the internal socket will be used.
* @return integer Number of affected rows.
* Returns number of rows in a result set.
* Note: This only works for statements returning a result set, for DML operations use AffectedRows() !
* @param resource $stmt The resource as returned from QueryResult()
* Returns last used auto_increment id.
* @param mixed $extsock Optionally an external SQLite socket to use. If not given the internal socket is used.
* @return integer The last automatic insert id that was assigned by the SQLite server.
* @see sqlite_last_insert_rowid()
* Commits current transaction.
* Note: Requires BEGIN TRANSACTION first!
* Without BEGIN TRANSACTION an auto-transaction is always auto-commited!
$this->Query('COMMIT TRANSACTION');
* Rollback current transaction.
* Note: Requires BEGIN TRANSACTION first!
* Without BEGIN TRANSACTION an auto-transaction is always auto-commited!
$this->Query('ROLLBACK TRANSACTION');
* Allows to set the handling of errors.
* - db_SQLite::DBOF_SHOW_NO_ERRORS => Show no security-relevant informations
* - db_SQLite::DBOF_SHOW_ALL_ERRORS => Show all errors (useful for develop)
* - db_SQLite::DBOF_RETURN_ALL_ERRORS => No error/autoexit, just return the mysql_error code.
* @param integer $val The Error Handling mode you wish to use.
* Returns the current error handling mode.
* @return integer The current error handling mode.
* @see SetErrorHandling()
* Function allows debugging of SQL Queries.
* $state can have these values:
* - db_SQLite::DBOF_DEBUGOFF = Turn off debugging
* - db_SQLite::DBOF_DEBUGSCREEN = Turn on debugging on screen (every Query will be dumped on screen)
* - db_SQLite::DBOF_DEBUFILE = Turn on debugging on PHP errorlog
* You can mix the debug levels by adding the according defines!
* @param integer $state The DEBUG Level you want to be set
* Returns the current debug setting.
* @return integer The debug setting (bitmask)
* Handles output according to internal debug flag.
* @param string $msg The Text to be included in the debug message.
if($this->SAPI_type !=
'cli')
$formatstr =
"<div align=\"left\" style=\"background-color:#ffffff; color:#000000;z-index:10000;\"><pre>DEBUG: %s</pre></div>\n";
$formatstr =
"DEBUG: %s\n";
* Retrieve last SQLite error number.
* @param mixed $other_sock Optionally your own connection handle to check, else internal will be used
* @return integer The SQLite error number of the last operation
public function GetErrno($other_sock = -
1)
* Retrieve last SQLite error description.
* @param mixed $other_sock Optionally your own connection handle to check, else internal will be used
* @return string The SQLite error description of the last operation
* Prints out SQLite Error in own <div> container and exits.
* Please note that this function does not return as long as you have not set DBOF_RETURN_ALL_ERRORS!
* @param string $ustr User-defined Error string to show
* @param mixed $var2dump Optionally a variable to print out with print_r()
* @see sqlite_last_error()
* @see sqlite_error_string()
$errnum =
$this->myErrno;
$this->myErrno =
$errnum;
$filename =
basename($_SERVER['SCRIPT_FILENAME']);
@error_log($this->appname.
': SQLite class error in '.
$filename.
': '.
$ustr.
' ('.
chop($errstr).
')',0);
return($errnum); // Return the error number
$this->SendMailOnError($errnum,$errstr,$ustr);
if($this->SAPI_type !=
'cli')
echo
("<br>\n<div align=\"left\" style=\"background-color: #EEEEEE; color:#000000;\">\n");
echo
("<font color=\"red\" face=\"Arial, Sans-Serif\"><b>".
$this->appname.
": SQLite class error occured!</b></font><br>\n<br>\n<code>\n");
echo
("\n!!! ".
$this->appname.
": SQLite class error occured !!!\n\n");
echo
($space.
"CODE: ".
$errnum.
$crlf);
echo
($space.
"DESC: ".
$errstr.
$crlf);
echo
($space.
"FILE: ".
$filename.
$crlf);
echo
($space.
"QCNT: ".
$this->querycounter.
$crlf);
echo
($space.
"INFO: ".
$ustr.
$crlf);
if($this->SAPI_type !=
'cli')
if($this->SAPI_type !=
'cli')
if($this->AdminEmail !=
'')
echo
("<br>\nPlease inform <a href=\"mailto:".
$this->AdminEmail.
"\">".
$this->AdminEmail.
"</a> about this problem.");
echo
("<div align=\"right\"><small>PHP v".
phpversion().
" / SQLite Class v".
$this->classversion.
"</small></div>\n");
if($this->AdminEmail !=
'')
echo
("\nPlease inform ".
$this->AdminEmail.
" about this problem.\n");
echo
("\nRunning on PHP v".
phpversion().
" / SQLite Class v".
$this->classversion.
"\n");
* Send error email if programmer has defined a valid email address and enabled it with the define SQLITEDB_SENTMAILONERROR.
* @param integer $merrno SQLite errno number
* @param string $merrstr SQLite error description
* @param string $uerrstr User-supplied error description
private function SendMailOnError($merrno,$merrstr,$uerrstr)
$sname =
(isset
($_SERVER['SERVER_NAME']) ==
TRUE) ?
$_SERVER['SERVER_NAME'] :
'';
$saddr =
(isset
($_SERVER['SERVER_ADDR']) ==
TRUE) ?
$_SERVER['SERVER_ADDR'] :
'';
$raddr =
(isset
($_SERVER['REMOTE_ADDR']) ==
TRUE) ?
$_SERVER['REMOTE_ADDR'] :
'';
$uagent =
(isset
($_SERVER['HTTP_USER_AGENT'])) ?
$_SERVER['HTTP_USER_AGENT'] :
'';
$server =
$sname.
' ('.
$saddr.
')';
$message =
"SQLite Class v".
$this->classversion.
": Error occured on ".
date('r').
" !!!\n\n";
$message.=
" APPLICATION: ".
$this->appname.
"\n";
$message.=
" AFFECTED SERVER: ".
$server.
"\n";
$message.=
" USER AGENT: ".
$uagent.
"\n";
$message.=
" PHP SCRIPT: ".
$_SERVER['SCRIPT_FILENAME'].
"\n";
$message.=
" REMOTE IP ADDR: ".
$clientip.
"\n";
$message.=
" DATABASE FILE: ".
$this->database.
"\n";
$message.=
"SQL ERROR MESSAGE: ".
$merrstr.
"\n";
$message.=
" SQL ERROR CODE: ".
$merrno.
"\n";
$message.=
" QUERY COUNTER: ".
$this->querycounter.
"\n";
$message.=
" INFOTEXT: ".
$uerrstr.
"\n";
$message.=
" SQL QUERY:\n";
$message.=
"------------------------------------------------------------------------------------\n";
$message.=
"------------------------------------------------------------------------------------\n";
if(defined('MYSQLDB_MAIL_EXTRAARGS') &&
MYSQLDB_MAIL_EXTRAARGS !=
'')
@mail($this->AdminEmail,'SQLite Class v'.
$this->classversion.
' ERROR #'.
$merrno.
' OCCURED!',$message,MYSQLDB_MAIL_EXTRAARGS);
@mail($this->AdminEmail,'SQLite Class v'.
$this->classversion.
' ERROR #'.
$merrno.
' OCCURED!',$message);
* Returns version of this class.
* @return string The version of this class.
return($this->classversion);
* Returns SQLite library version.
* @return string SQLite library version.
* Escapes a given string with the 'sqlite_escape_string' method.
* Always use this function to avoid SQL injections when adding dynamic data to SQLite!
* This function also handles the settings for magic_quotes_gpc, if
* this setting is enabled it will call stripslashes() first.
* @param string $str The string to escape.
* @return string The escaped string.
* Returns amount of queries executed by this class.
* @return integer Querycount
return($this->querycounter);
* Returns amount of time spend on queries executed by this class.
* @return float Time in seconds.msecs spent in executin MySQL code.
return($this->querytime);
* Returns microtime in format s.mmmmm.
* Used to measure SQL execution time.
* @return float the current time in microseconds.
Documentation generated on Sat, 07 Aug 2010 20:01:01 +0200 by phpDocumentor 1.4.3