You are on page 1of 84

SQLite Using

PHP & PDO

Reference

byJanZumwalt
Otherreferencesavailableatwww.neatinfo.com/dev_notes/_cheatsheets

Notes
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg2 of84
SqLiteReferenceCopyright20052015

TableofContents

Section1Introduction.......................................................................................................................................................6
AboutThisReference...............................................................................................................................................................................6
WhatisPDO.............................................................................................................................................................................................6
SQLite2VSSQLite3..................................................................................................................................................................................6
WhatdatabasedoesPDOsupport?.........................................................................................................................................................7
Settingupadevelopmentsystem...........................................................................................................................................................7
XAMPPconfigfiles...................................................................................................................................................................................8
Databasemanagers.................................................................................................................................................................................8
DoIhavePDOonmycomputer?.............................................................................................................................................................9
GoodProgrammingSyntax....................................................................................................................................................................10
Comments.........................................................................................................................................................................................10
SingleRowData................................................................................................................................................................................10
MultipleRowData............................................................................................................................................................................11

Section2DataTypes........................................................................................................................................................12
Section3SimpleDatabaseExample................................................................................................................................13
Connectanderrorhandling...................................................................................................................................................................13
CreateandInsertIntoDatabase............................................................................................................................................................13
ViewandSearchData............................................................................................................................................................................14
UpdateData...........................................................................................................................................................................................15
DeleteData............................................................................................................................................................................................16

Section4DATABASE(manipulation)...............................................................................................................................17
AddDatabase.........................................................................................................................................................................................17
CopyDatabase.......................................................................................................................................................................................17
DeleteDatabase....................................................................................................................................................................................18
RenameDatabase..................................................................................................................................................................................18
DatabaseDescriptions...........................................................................................................................................................................19
MasterDatabase....................................................................................................................................................................................19
CommandLine..................................................................................................................................................................................19

Section5TABLE(manipulation).......................................................................................................................................23
AddTable...............................................................................................................................................................................................23
DoesTableExist.....................................................................................................................................................................................23
CopyTableWithData............................................................................................................................................................................24
CopyTableStructure.............................................................................................................................................................................25
DeleteTable...........................................................................................................................................................................................26
RenameTable........................................................................................................................................................................................26
ViewTableStructures............................................................................................................................................................................26
TableDescription...................................................................................................................................................................................27

Section6ROW/RECORD(manipulation).......................................................................................................................29
InsertRow(add)....................................................................................................................................................................................29
Fillingallfields..................................................................................................................................................................................29
Selectingspecificfieldstofill............................................................................................................................................................29
InsertMultipleRows............................................................................................................................................................................29
CopyRow...............................................................................................................................................................................................29
DeleteAllRows......................................................................................................................................................................................29
DeleteRow(s)MatchingCondition........................................................................................................................................................29
UpdateRow(s)MatchingCondition.......................................................................................................................................................30
SQLUPDATEWarning.......................................................................................................................................................................31
CountRows............................................................................................................................................................................................31
CountColumns......................................................................................................................................................................................31
IndexDescription...................................................................................................................................................................................31

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg3 of84
SqLiteReferenceCopyright20052015

Section7COLUMN/FIELD(manipulation).....................................................................................................................33
AddColumn...........................................................................................................................................................................................33
CopyColumnanddata...........................................................................................................................................................................33
DeleteColumn.......................................................................................................................................................................................33
RenameColumn....................................................................................................................................................................................33
CountColumns......................................................................................................................................................................................33

Section8SEARCHES/SHOW(manipulation)..................................................................................................................35
SimpleSelectSyntax..............................................................................................................................................................................35
Thefourfetchtypes...............................................................................................................................................................................35
WHERE..............................................................................................................................................................................................36
SHOWRECORDONSINGLELINE.......................................................................................................................................................36
LIKE...................................................................................................................................................................................................37
AND...................................................................................................................................................................................................37
OR.....................................................................................................................................................................................................37
AdvancedSelectSyntax.........................................................................................................................................................................37
LIMIT.................................................................................................................................................................................................37
ORDERBY..........................................................................................................................................................................................38
GROUPBY.........................................................................................................................................................................................38
HAVING.............................................................................................................................................................................................39
DISTINCT...........................................................................................................................................................................................39
FindingDuplicates............................................................................................................................................................................39
DELETEINGDuplicates......................................................................................................................................................................40

Section9Debug&Errors.................................................................................................................................................41
ErrorCodes............................................................................................................................................................................................41
1)Ifyoucopiedcodefromapageofthisreference............................................................................................................................41
2)SomeSQLiteversionshaveincompatibilities...................................................................................................................................41
3)"Invalidresource"error...................................................................................................................................................................42
4)Sensitivitytowhitespace................................................................................................................................................................42
5)unabletoopenfile.......................................................................................................................................................................42
6)SQLITE_CORRUPTerror................................................................................................................................................................42
7)WHEREClauseerror.....................................................................................................................................................................42
8)Unexpectedreturnvalue,i.e.Array.............................................................................................................................................42
9)SYNTAXERROR,UnexpectedEnd..............................................................................................................................................43
10)unexpectedT_VARIABLE............................................................................................................................................................43

Section10VIEWS(custom)..............................................................................................................................................44
Section11TRIGGERS(manipulation)...............................................................................................................................45
InsertRowTimestamp...........................................................................................................................................................................45
LoggingAllInserts,Updates,andDeletes..............................................................................................................................................45

Section12TRANSACTIONS..............................................................................................................................................48
Section13JOINS..............................................................................................................................................................49
CROSSJOIN............................................................................................................................................................................................50
INNERJOIN............................................................................................................................................................................................51
LEFTOUTERJOIN...................................................................................................................................................................................51
RIGHTOUTERJOINandFULLOUTERJOIN.............................................................................................................................................52
UNION....................................................................................................................................................................................................52

Section14DateandTime................................................................................................................................................53
FunctionFormat....................................................................................................................................................................................53
Modifiers...............................................................................................................................................................................................54
Timestamp.............................................................................................................................................................................................55
Examples................................................................................................................................................................................................55
Savecurrentorfuturedate...............................................................................................................................................................56
Lessthantimespan..........................................................................................................................................................................56
Dateequaltotimespan....................................................................................................................................................................56
TimeZone..............................................................................................................................................................................................56

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg4 of84
SqLiteReferenceCopyright20052015

ErrorsandBugs......................................................................................................................................................................................57

Section15Strings............................................................................................................................................................58
ListofStringFunctions...........................................................................................................................................................................58
sqlite_escape_string($string)................................................................................................................................................................60
TextScrubbing.......................................................................................................................................................................................60

Section16Math..............................................................................................................................................................62
ListofMathFunctions...........................................................................................................................................................................62
MathExamples......................................................................................................................................................................................63
Money....................................................................................................................................................................................................63

Section17ImagesSavingandDisplaying.......................................................................................................................65
TestImage.............................................................................................................................................................................................65
SavinganImage.....................................................................................................................................................................................66
DisplayanImage....................................................................................................................................................................................66

Section18Crypt,Hash,etc..............................................................................................................................................69
FunctionSyntax.....................................................................................................................................................................................69
FileIO.....................................................................................................................................................................................................69

Section19PrintingTableData.........................................................................................................................................70
FormattedHTMLTable..........................................................................................................................................................................70
Tableprint.............................................................................................................................................................................................70
Simpleprint_r........................................................................................................................................................................................71
Loopprint_r...........................................................................................................................................................................................71
Vardump...............................................................................................................................................................................................72
Index&associativetableoutput...........................................................................................................................................................73

AppendixATestDatabases.............................................................................................................................................75
Testdatabaseprogram..........................................................................................................................................................................75

AppendixBCommandReference...................................................................................................................................77
PDOCommands.....................................................................................................................................................................................77
SQLite3Commands................................................................................................................................................................................78

AppendixCReservedWords(337).................................................................................................................................80
Documenation.......................................................................................................................................................................................84
References.............................................................................................................................................................................................84

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg5 of84
SqLiteReferenceCopyright20052015

Section1
Introduction
AboutThisReference
ThisreferencewaswrittenduringthedesignofaprojectthatdidnotneedthehugeoverheadofaMySqldatabase.When
IresearchedSQLite,Ifoundtheexistingexamplesveryconfusing.Itwashardtotellthedifferencebetweencode
designedfortheUnixorWinshellcommandlineinterfaceC,SQLite2,orSQLite3.
IdecidedtousePDObecauseIalreadyhadyearsofexperiencewithproceduraldatabaseprogrammingandwantedto
widenoutwithobjectoriented(OOP)databaseprogramming.
ThisreferencehasspecificexamplestestedintheXAMPPdevelopmentenvironmentbutshouldbeabletobeusedon
justaboutanyHTTPserverwithoutmodification.
SQLite3isusedforthedatabase,HTMLandJavaScriptareusedfortheuserbrowserinterface,PHPisusedforserverfile
accessandPHPPDOallowsPHPtocommunicatewiththeSQLitedatabase.Whew!Thatwasamouthful,butitallworks
easilyandverywelltogether.
Themethodologyjustmentionedisbyfarthemostcommoninuseontheinternettoday.Thankfully,onlybasiccomputer
skillsandterminologywillbeneeded.Examplesarespecificallydesignedforeaseofunderstanding.Flashycosmeticweb
designhasbeenleftoutforclarity.
Sincetheoriginalversionofthisguide,SmartPhonetechnologyhasembracedSQLIte.TheAndroidphoneOSis
particularlysuitedtoSQLiteuse.However,thisguideisintendedtobeleanandmeansospecificSmartPhoneapplication
isnotshown.

Besuretoreviewthemostcommonerrorsneartheendofthisdocumentbeforeproceeding.

WhatisPDO
PDO(PHPDataObjects)isaPHPextensionthatsupportsdatabaseconnectionswithauniformcommandstructure.This
allowsdeveloperstocreatecodewhichisportableacrossmanydatabasesandsystemoperatingplatforms.Simply
explained,PDOletsyouusethesamecode(objectoriented)orcommandsforaprojectthatcouldbeusedonacell
phone,Applecomputer,Windows,oranIBMmainframe.Thatmakesprogrammingaloteasier!

SQLite2VSSQLite3
NowtheBADnews!
ThevolunteersthatmaintainSQLitewantedasmalllightweightfeaturerichdatabasethatwouldcomparetoMySql.
SQLitetakeslessthan1mbofdiskstoragespacecomparedto80100mbforMySql.TokeepSQLiteleanandmeanthe
developerschosetoforfeitcomplicatedmultitaskingandmultiusercriteriathatloadeddownMySql.Thisisnota
problem,itisafeature.Atsomepoint,someoftheoriginalwaysofdoingthingsinearlierversionsofSQLitebecamesuch
aproblemthattheydecidedtocreateanentirelynewcommandanddatabasestructurebetweenversion2&3.
ThelargestchangesstartedwithSQLite3andthatsaBIGproblem.ThechangesinSQLite3causemuchofthesourcecode
ofearlierversionstobeincompatibilitywithnewerversionsofSQLIte;neitherthedatabaseorcommandstructures
worksmoothlyacrosstheseversions.
ThesolutionchosenbySQLitevolunteerswastostartSQLite3asanewDBlanguage;henceweendedupwithPDO.As
aconsequenceofthesedifferences,wemustusecautioninchoosingthecommandsanddatabasestructure.Thegood
newsisthecommandsareeasilyrecognized;SQLite3commandsuse=>objectsyntax.

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg6 of84
SqLiteReferenceCopyright20052015

Whatisnotalwayseasytorecognizeisthedatabasestructure(type).ManySQLItedatabaseshavenoextensionor
genericextensionsthatdonotofferanyclueastowhatsetofcommandsshouldbeusedonthem,sobecareful!
SQLite(likemostotherDBlanguages)offersasetofcommandlineoptions.ThecommandlineandPDOcommandsare
notinterchangeablesowatchout!
Hereisacomparisonofcommandstoopenorcreateadatabase.
Default

SQLite2:

$db = new SQLiteDatabase('test.sqlite2', 0666, $error);

PDO SQLite2:

$db = new PDO("sqlite2:test.sqlite2");

Command line SQLite2:

sqlite

test. Sqlite2

Command line SQLite3:

sqlite3

test. sqlite3

PDO SQLite3:

$db = new PDO("sqlite:test.sqlite3");

Listing1.1Versioncommandcomparison.

WhatdatabasedoesPDOsupport?
PDOsupportsmanyofthepopulardatabases.Hereisapartiallist...

DBLIB:FreeTDS/MicrosoftSQLServer/Sybase
Firebird(http://firebird.sourceforge.net/):Firebird/Interbase6
IBM(IBMDB2)
INFORMIXIBMInformixDynamicServer
MYSQL(http://www.mysql.com/):MySQL3.x/4.0
OCI(http://www.oracle.com):OracleCallInterface
ODBC:ODBCv3(IBMDB2andunixODBC)
PGSQL(http://www.postgresql.org/):PostgreSQL
SQLITE(http://sqlite.org/):SQLite3.x

Settingupadevelopmentsystem
Youwillneedadevelopmentenvironment.IstronglyrecommendusingXAMPPforeitherWindowsorLinux.Priorto
about2007,WAMPhadmorefeaturesandlessinstallationproblemsthanXAMPP,butthatisnolongertrue.Ihaveused
bothXAMPPandWAMPformanyyearsandfindthatXAMPPhaslessinstallationproblems.AfewyearsagoXAMPPhad
somecontrolpanelissueswhichseemtohaveallbeenfixed.Fordownloadsandfurtherreading,seethelinksbelow.
http://www.apachefriends.org/en/xampp.html
http://www.wampserver.com/en/

Most(butnotall)LinuxdevelopmentsystemscomewithPHPsupportforSQLite.Onwindowsmachines,XAMPPinstalls
PHPsupportforSQLite2butnotnecessarilySQLite3.
IfyouhavetroublewithSQLite3,thefirstthingyoushouldcheckisthePHPconfigfile.Dontforgettocheckallthe
possiblelocationsgivenbelow.Also,youshouldstoptheApacheserverbeforeeditinganyfilethataffectsApache,and
thenrestartafteryouaredone.
Windows:

xampp/php/php.ini.

Some Linux xampp/apache/bin/php.ini

TheWindowsconfigfileshouldhaveacoupleareaswithlinesthatlooklikethefollowing
extension=php_pdo_sqlite.dll
extension=php_pdo_sqlite_external.dll
extension=php_sqlite.dll
extension=php_sqlite3.dll
sqlite.assoc_case = 0

Theselinesshouldnothavethe;(semicolon)atthestartoftheline.Thesemicoloncommentsoutthecodeandprevents
itfromworking.Ifithasthesemicolon;itshouldbeeditedout.Linuxmayhaveslightlydifferentvaluesandfilenames
thatendwith.soontheend.
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg7 of84
SqLiteReferenceCopyright20052015

XAMPPconfigfiles
Justtomakethissectioncomplete,alistofconfigurationfilesforXAMPPareprovidebelow.Aswealreadymentioned,
theremaybeslightdifferencesinlocationornamesdependingonwhetheritisaWindowsorLinuxinstallation.Many
Linuxdevelopersslightlymodifythedirectorystructure.
*
*
*
*
*
*

Apache
Apache
Apache
Apache
Apache
PHP:

basic configuration:
SSL:
Perl
(addon):
Tomcat (addon):
Python (addon):

*
*
*
*
*

MySQL:
phpMyAdmin:
FileZilla FTP:
Mercury Mail:
Sendmail:

.\xampp\apache\conf\httpd.conf
.\xampp\apache\conf\ssl.conf
.\xampp\apache\conf\perl.conf
.\xampp\apache\conf\java.conf
.\xampp\apache\conf\python.conf
.\xampp\php\php.ini
.\xampp\apache\bin\php.ini
.\xampp\mysql\bin\my.cnf
.\xampp\phpMyAdmin\config.inc.php
.\xampp\FileZillaFTP\FileZilla Server.xml
.\xampp\MercuryMail \MERCURY.INI
.\xampp\sendmail\sendmail.ini

Linuxmayhaveslightlydifferentvaluessuchasnameswith.soontheend.

Databasemanagers
Customprogrammingisprobablyonlyabout1020%ofadatabaseprogrammerswork.Theother80%isdoneusinga
convenientdatabasemanagerprogram.Severalgoodonesarelistedbelow.

SQLite2009 Pro Enterprise Manager http://osenxpsuite.net/


Firefox SQLITE plugin module

http://code.google.com/p/sqlite-manager/

SQLIite Administrator

http://sqliteadmin.orbmu2k.de/

SQLite Browser
SqliteRoot
Phpliteadmin

http://sqlitebrowser.sourceforge.net/ great for beginners


http://sqliteroot.com/
http://code.google.com/p/phpliteadmin/

Atthetimeofthiswriting,https://sourceforge.nethadover500highqualityfreeSqLiteutilities.TheGooglecode
developersitehttp://code.google.comisanothergoodplacetolook.Theyareallworthcheckingout.Aninternetsearch
willcertainlyturnupmoretreasure.Forexample,thereareseveralutilitiesthatmakemanagingadatabaseoverthe
internetmucheasier.

PhpLiteAdmindoesnotrequireinstallationorconfiguration.Itisasmallsinglefilethatisplacedinthedirectorywhere
yourdatabaseislocated.IrecommendthisforthebeginneranditiswhatIusemostofthetime.ItsupportsbothSqLite2
andSqLite3(severalothermanagersdont).Ithasasimpletopmenuarrangedandlabeledintuitively.
https://bitbucket.org/phpliteadmin/public/

SQLite2009ProIuse(freewareversion)someofthetime.SQLite2009Prohasallthefeaturesyoucouldpossiblywant
includingbuiltindocumentation.Ittakessomegettinguseto;especiallyfiguringoutyourdatahierarchyandwhereyour
tableinformationislocated.TheinstallationcreatesaSQLitefileextensiontypethatopensthemanagerimmediatelyif
themouseclicksonadatabasefile.
http://sqlite2009pro.azurewebsites.net/

SQLiteAdministratorisoneoftheeasiestmanagerstouseandIwouldpreferitexceptthatitismissingacouplekey
features.Itisnoteasytoaddoreditarecord.Iwouldnotbesurprisedifayearormoreofdevelopmentfixesmostofits
issues.TheinstallationcreatesaSQLitefileextensiontypethatopensthemanagerimmediatelyifthemouseclicksona
databasefile.
http://sqliteadmin.orbmu2k.de/

FirefoxPluginwouldbeasuperiorchoiceexceptthattheFirefoxbrowsermustberunningbeforeyouselectadatabase
filetoworkon.Withthebrowserrunning,youmustselectamenuthenatoolbutton,afterwardsyoucanclosethe
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg8 of84
SqLiteReferenceCopyright20052015

Firefoxbrowserandthemanagerwillremainindependent.ThisisabitclumsyandpreventsanassociationoftheSQLite
fileextensiontobemadethatattachestothemanagertool.Thatbeingsaid,itiseasytouseandiswelllaidout.

SQLiteBrowserisaverycleaneasytousemanager.Itisintuitiveandthingsareextremelyeasytofind.Theuserhasthe
optionofselectingfromasetofwizardsanditprovidesapleasingspreadsheetlikeinterface.Windowsallowsyouto
createaSQLitefileextensionsothatamouseselectionopensthemanagerimmediately.
http://sqlitebrowser.org/

DoIhavePDOonmycomputer?
Onceyouhaveadevelopmentenvironmentupandrunning,youshouldcheckifthePHPPDOdriverisinstalledforyour
database.Checkphpinfo()forasectionnamedSQLITEandPDO.Youmayalsochecktheavailabledriverswiththe
staticmethodPDO::getAvailableDrivers(),examplesaregivenbelow
<?php
echo '<h2>PHP Info</h2>';
phpinfo();
?>

Listing:1.2AllthePHPinfoyoucouldpossiblywant!
<?php
echo '<h2>PDO Info</h2>';
foreach(PDO::getAvailableDrivers() as $driver) {
echo $driver.'<br />';
}
?>

Listing:1.3ShowalistofPDOsupporteddatabasesonyourcomputer.
<html>
<body style="font-family:arial;">
<h2>PDO & PHP Info</h2>
</blockquote>
<span style="color:red;">
<?php
foreach(PDO::getAvailableDrivers() as $driver)

echo $driver.'<br />';


}
?>
</span>
</blockquote>
If you see "<span style="color:red;">sqlite2</span>" listed, there is support for sqlite2.<br><br>
If you see "<span style="color:red;">sqlite</span>" listed, there is support for sqlite3.<br><br>
PHP version: <span style="color:red;"><?php echo phpversion(); ?></span><br>
SQLite library version: <span style="color:red;"><?php echo sqlite_libversion(); ?></span><br>
SQLite library character encoding: <span style="color:red;"><?php echo sqlite_libencoding();
?></span><br>
<?php
echo "If you dont see an error message,
was created.<br><br>";
#

a <span style='color:red;'>SQLite3</span> test database

create test SQLite3 database

$query = " test.sqlite3;


$db = new PDO("sqlite:$query") or die("Could not create:

<span style='color:red;'>$query</span>");

?>

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg9 of84
SqLiteReferenceCopyright20052015

<!--

uncomment the next line to see the comprehensive PHP information

<!--

PhpInfo: <span style="color:red;"><?php echo phpinfo(); ?></span><br><br>

-->
-->

</body>
</html>

Listing:1.4FancyreportwithanoptionforacomprehensivePHPlisting.
PHP and SQLite3 Information
Supported PHP Data Object (PDO) drivers.
mysql
odbc
sqlite
sqlite2
Note: If you see "sqlite", then there is support for sqlite3.
PHP version: 5.3.1
SQLite library version: 2.8.17
SQLite library character encoding: iso8859
If you dont see an error message, a SQLite3 test database was created.

OUTPUTViewgeneratedonaWinXPXAMPPsystem.(Thephpinfoisnotshownandisabout3pageslong).

GoodProgrammingSyntax
Afrequentlyusedstandardistoassignavariablenamed$rowforsinglerowdataretrievaland$rows(noticethe's')for
multiplerowdata.Multiplerowsofdataaresometimescalledadatasetorresultset.

COMMENTS
Singleroworendofrowcommentsstartwithadoubledash".MultilinecommentsusethetypicalCstylecomment,
/*text*/.
$query = "CREATE TABLE salespeople (
-- single row comment
/*
Comment that spans
More than one line */
id INTEGER PRIMARY KEY,
first_name TEXT NOT NULL, -- end of row comment
last_name TEXT NOT NULL /* you can also do this */
) ";

SINGLEROWDATA
Asinglerowofdataisretrievedbyusingthefetch()statement.Becarefulnottoconfuseitwiththefetchall()statement.
Thefollowingisageneralexample.
$query = "SELECT * FROM t1";
$result = $db->query("$query") or die("Error in query:

<span style='color:red;'>$query</span>");

$row = $result->fetch();

Listing:1.5Gettingasinglerowofinformationasanarray.
Eventhoughtheremaybemorethanonematch,onlythefirstmatchonewillbereturnedin$row.
Wecanaccessthissinglerowofdatabyusingtheassociativefieldname.
echo $row['name'];

Listing:1.6Showingacolumnfromrowdata.
Thiswouldreturn"Frank"becausethathasthelowestIDnumberandwouldbethefirstmatch.
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg10 of84
SqLiteReferenceCopyright20052015

MULTIPLEROWDATA
Multiplerowsofdatacanberetrievedasanarraybyusingthefetchall()statement.Becarefulnottoconfuseitwiththe
fetch()statement.Theresultisreturnedasanarrayofarrays.Thefollowingisageneralexample.
$query = "SELECT * FROM t1";
$result = $db->query("$query") or die("Error in query:

<span style='color:red;'>$query</span>");

$rows = $result->fetchall();

Listing:1.7Gettingmultiplerowsofinformationasanarrayofarrays.
Wecanaccessanyrowusingarraymatrixaddressing.
echo $rows['3'],['name'];

Listing:1.8Showinganycolumnofanarrayofarrays.
Thiswouldaccessthethirdrowofinformationandreturnthenamedata.

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg11 of84
SqLiteReferenceCopyright20052015

Section2
DataTypes
EachcolumninaSQLite3databaseisassignedoneofthefollowingtypeaffinities:

BLOB
INTEGER
NULL
NUMERIC
REAL
TEXT

Typename from
CREATE TABLE statement
BLOB
INT
INTEGER
TINYINT
SMALLINT
MEDIUMINT
BIGINT
UNSIGNED BIG INT
INT2
INT8
NULL
NUMERIC
DECIMAL(10,5)
BOOLEAN
DATE
DATETIME

Resulting
Assignment
BLOB

INTEGER

NULL

NUMERIC

Description
A Binary Long Object, i.e. images

A number without decimals, a whole number.

Unassigned

A number with or without decimals

REAL
DOUBLE
DOUBLE PRECISION
FLOAT

REAL

A 'floating point' number, a number with decimals

CHARACTER(20)
VARCHAR(255)
VARYING CHARACTER(255)
NCHAR(55)
NATIVE CHARACTER(70)
NVARCHAR(100)
TEXT
CLOB

TEXT

Text that can contain both numbers and letters

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg12 of84
SqLiteReferenceCopyright20052015

Section3
SimpleDatabaseExample
ThissectionprovidessimpleexamplesofmostdatabasecommandsusedbyPDO.Theexampleprovidestheskeletal
frameworkonwhichmanydatabases,includingacompanyemployeedatabasesorphonecontactlistcanbemade.Itisa
veryvaluablereferenceonitsown.Thestepstocreatingasimpledatabaseare
Design
Create db File
Create table and column definitions
Insert data
View and search data
Update data
Delete data

Connectanderrorhandling
Inallourexamples,weassumethatwehavesuccessfullycreatedand/orconnectedtothedatabaseandsetupourerror
handling.Agoodgenerictemplateisgivenbelow
/*

Listing 2.1 - create "people db

*/

echo '<body style="font-family:arial;">';


echo '<h2>Create "people" database</h2>';
#

setup

$dbPath

= $_SERVER['DOCUMENT_ROOT'] . "/contacts/";

$dbFile

= "people.sqlite3";

connect to SQLite3 database


$query = "$dbPath$dbFile";
try { $db = new PDO("sqlite:$query"); }
catch(PDOException $e) { echo $e->getMessage()." Error: <span style='color:red;'>$query</span>";

}
#

enhanced error messages


$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Listing:2.1Genericconnectionanderrorhandling.
Fromthispointon,wewillalwaysassumetheprogrammerknowsthatthenecessarycodetoconnecttothedatabase
(similartowhatisshownhere)needstobeinsertedforthedbconnection.

CreateandInsertIntoDatabase
Oncetheerrordefinitionismade,wedontneedtousethetry{},catch{},ordiecodeanymore.ThePDOerror
reportingdoesawonderfuljobonfatalerrors,butcanbealittlecrypticforwarnings.Ihavefoundacombinationofthe
twotechniquesworksbest.Anexampleoftypicalerrorsupportthatincludessqlitespecificinformationisprovidedhere.
$result = $db->query("$query")

or die("Error in query: <span style='color:red;'>$query</span>");

Listing:2.2Typicalerrorsupport.
<?php
/*

Listing 2.3 - create "people db

*/

echo '<body style="font-family:arial;">';


echo '<h2>Create "people" database</h2>';
#

connect to database

# ... code to setup, connect to database, and handle errors goes here

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg13 of84
SqLiteReferenceCopyright20052015

create table
$query = "CREATE TABLE friends (
id INTEGER PRIMARY KEY NOT NULL,
active

TEXT(1),

-- y/n

updated
name

TEXT(25),

phone TEXT(25),
editby TEXT default 'unknown',
editdate TEXT default (datetime('now','localtime')
)";
$result = $db->query("$query") or die("Error in query: <span style='color:red;'>$query</span>");
echo "<i>Database successfully initialized.<br></i> ";
# multiple row data insert
$query = "insert into 'friends' (name, phone)
select 'James Bond','007-1234'
union select 'Mickey Mouse','(200) 100-1122'
union select 'Daffy Duck','200 100-1122' ";
$result = $db->query("$query") or die("Error in query: <span style='color:red;'>$query</span>");
# single row data insert
$query = "insert into 'friends' (name, phone) values ('Porky Pig', '200) 100-1122') ";
$result = $db->query("$query") or die("Error in query: <span style='color:red;'>$query</span>");
#

show success
echo "<i>Data successfully inserted.</i><br>";

show number of rows affected by last operation


$rows_affected = $result->rowCount();
echo "<span style='color:red;'>$rows_affected</span> records affected ";

close db, PHP will also do this automatically


$db = NULL;

?>

Listing:2.3createandinsertdata

ViewandSearchData
Hereisourcompletedcodetoviewalltabledata.
<?php
/*

Listing 2.4 search techniques

*/

echo '<body style="font-family:arial;">';


echo '<h2> Search Techniques </h2>';
#

connect to database

# ... code to setup, connect to database, and handle errors goes here
#

query using simple SELECT


$query = "SELECT * FROM 'friends'";
$result = $db->query($query) or die("Error in query: <span style='color:red;'>$query</span>");
$row = $result->fetchall(PDO::FETCH_ASSOC);

show table data

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg14 of84
SqLiteReferenceCopyright20052015

foreach($row as $array) {
echo "<pre>";
print_r($array);
echo "</pre>";
}
echo 'Result for: $query = "SELECT * FROM \'friends\' ";'. "<br>";
#

show number of rows affected by last operation


$rows_affected = $result->rowCount();
echo "<span style='color:red;'>$rows_affected</span> records affected<br><br>";
echo "------<br>";

query using specific fields and SELECT with WHERE


$query = "SELECT 'phone' FROM 'friends' WHERE name='James%' ";
$result = $db->query($query) or die("Error in query: <span style='color:red;'>$query</span>");
$row = $result->fetchall(PDO::FETCH_ASSOC);

show table data


foreach($row as $array) {
echo "<pre>";
print_r($array);
echo "</pre>";
}
echo 'Result for: $query = "SELECT phone FROM 'friends' WHERE name=\'James%\' ";. "<br>";

show number of rows affected by last operation


$rows_affected = $result->rowCount();
echo "<span style='color:red;'>$rows_affected</span> records affected<br><br>";

show success
echo "<i>Search successful.</i><br>";

close db, PHP will also do this

automatically

$db = NULL;
?>

Listing2.4searchtechniques

UpdateData
IfweuseWHEREnameLIKE'James%'thenanynamestartingwithJameswillbeselected.
Sohereiswhatweneed
<?php
/* Listing 2.5.- updating James
#

*/

connect to database

# ... code to setup, connect to database, and handle errors goes here
#

update table data


$query = "UPDATE 'friends' SET phone='911-007-1234' WHERE name LIKE 'James%'";
$result = $db->query("$query") or die("Error in query: <span style='color:red;'>$query</span>");

show success
echo "<i>Update data was successful.</i><br>";

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg15 of84
SqLiteReferenceCopyright20052015

Return rows affected by last operation


$rows_affected = $result->rowCount();
echo "<span style='color:red;'>$rows_affected</span> records affected ";

close db, PHP will also do this

automatically

$db = NULL;
?>

Listing:2.5finalversionofupdatingarecord

DeleteData
IfweuseWHEREnameLIKE'James%'thenanynamestartingwithJameswillbeselected.InsteadwewilluseWHERE
nameLIKE'%Bond%'thenonlyanamewiththislastnamewouldbedeleted.
Sohereiswhatweneed
<?php
/* Listing 2.6 - delete James Bond

*/

echo '<body style="font-family:arial;">';


echo '<h2>Update friends table data</h2>';
#

connect to database

# ... code to setup, connect to database, and handle errors goes here
#

delete row ofdata


$query = "DELETE from 'friends' WHERE name LIKE '%Bond%'";
$result = $db->query("$query") or die("Error in query: <span style='color:red;'>$query</span>");

show success
echo "<i>Data deleted successful.</i><br>";

Return rows affected by last operation


$rows_affected = $result->rowCount();
echo "<span style='color:red;'>$rows_affected</span> records affected ";

close db, PHP will also do this

automatically

$db = NULL;
?>

Listing:2.6deletearowofinformationbasedonsearchcriteria

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg16 of84
SqLiteReferenceCopyright20052015

Section4
DATABASE(manipulation)
Anoftenoverlookedaspectofdatabaseprogrammingisthemaintenancethatusuallycontinuestobeanongoingafter
thedatabaseiscreated.Commandstomanipulatethewholedatabasefileorrevealthedefinitionsofitstablesor
columnsarenecessarytodothis.

AddDatabase
RememberthatifSQLitedoesnotfindthedatabasegiveninthefilename,itwillattempttomakeit.Soallthatisneeded
tocreateanewdbistohaveavalidpathandsupplyanewfilename.
IfyoudonotwantPDOtocreateanemptydbwhennoneisfound,youcanusephpsfile_existscommandtotestforthe
file.
$datafile = '/path/to/test.sqlite3';
if (file_exists($datafile)) {
... code to
... connect to database
} else {
echo "Error, did not find database at $datafile.";
exit;
}

Listing:3.1Testingifadatabaseexists
Heisaprogramlistingthatopensadborcreatesanewoneifnoneisfound.
<?php
/* Listing 8.1 add db

*/

echo '<body style="font-family:arial;">';


echo '<h2>Add or connect to database</h2>';
#

setup
$dbPath

= $_SERVER['DOCUMENT_ROOT'] . "/path/to/db/";

$dbFile

= "db_name.sqlite3";

make or connect to SQLite3 database


$query = "$dbPath$dbFile";
try { $db = new PDO("sqlite:$query"); }
catch(PDOException $e) { echo $e->getMessage(); }
echo "<i>Database successfully initialized.<br></i> ";

close db, PHP will also do this

automatically

$db = NULL;
?>

Listing:3.2Creatinganewdatabase

CopyDatabase
Atthetimeofwritingthisreference,IwasunabletofindaPDOdbcopycommand.However,therearestillseveral
optionsavailable.

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg17 of84
SqLiteReferenceCopyright20052015

1allthedbmanagersprovideanimportfeature
2adatabasecouldbeopenedanditcontentsmeticulouslycopied
3usephptomakeacopyofthefile
Ifavormethodthree(3).Hereisanexample
<?php
/* Listing 8.2 copy a db

*/

echo '<body style="font-family:arial;">';


echo '<h2>Copy database</h2>';
#

setup
$dbPath
$dbFile
$dbNew

= $_SERVER['DOCUMENT_ROOT'] . "/contacts/";
= "people.sqlite3";
= "test.sqlite3";

copy SQLite database


copy("$dbPath$dbFile", "$dbPath$dbNew")
or die("Error copying db: <span style='color:red;'>$dbFile to $dbNew</span>");

show success
echo "<i>Database copied successfully.</i><br>";

?>

Listing:3.3Copyadatabase

DeleteDatabase
Atthetimeofwritingthisreference,IwasunabletofindaPDOdbdeleteordropcommand.However,therearestill
severaloptionsavailable.
1dbmanagersmayprovideadeletefeature
2adatabasecouldbeopenedanditcontentsmeticulouslydeleted
3usephptodeletethedatabasefile.
Ifavormethodthree(3).Hereisanexample
<?php
/* Listing 8.3 delete a db

*/

echo '<body style="font-family:arial;">';


echo '<h2>Delete database</h2>';
#

setup
$dbPath
$dbFile

= $_SERVER['DOCUMENT_ROOT'] . "/contacts/";
= "test.sqlite3";

# delete file (database)


unlink("$dbPath$dbFile")
or die("Error deleting dataebase: <span style='color:red;'>$dbPath$dbFile</span>");
#

show success
echo "<i>Database deleted successfully.</i><br>";

?>

Listing:3.4Deleteadatabase

RenameDatabase
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg18 of84
SqLiteReferenceCopyright20052015

Atthetimeofwritingthisreference,IwasunabletofindaPDOdbrenamecommand.However,therearestillseveral
optionsavailable.
1dbmanagersmayprovidearenamefeature
2adatabasecouldbeopenedanditcontentscopiedtoanewdatabase,thentheolddbdeleted
3usephptorenamethedatabasefile
Ifavormethodthree(3).Hereisanexample
<?php
/* Listing 8.4 rename db

*/

echo '<body style="font-family:arial;">';


echo '<h2>Rename database</h2>';
$dbPath

= $_SERVER['DOCUMENT_ROOT'] . "/contacts/";

$dbFile
$dbNew
#

= "people.sqlite3";
= "test.sqlite3";

copy SQLite database


rename("$dbPath$dbFile", "$dbPath$dbNew")
or die("Error renaming db: <span style='color:red;'>$dbFile to $dbNew</span>");

show success
echo "<i>Database renamed successfully.</i><br>";

?>

Listing:3.5Deleteadatabase

DatabaseDescriptions
MasterDatabase
EverySQLitedatabasehasanSQLITE_MASTERtablethatdefinestheschemaforthedatabase.TheSQLITE_MASTERtable
isreadonly.YoucannotchangethistableusingUPDATE,INSERT,orDELETE.Thetableisautomaticallyupdatedwhenyou
useCREATETABLE,CREATEINDEX,DROPTABLE,andDROPINDEXcommands.
OnethingthatisparticularlyusefulaboutusingthiscommandisthatwearegiventheSQLqueryneededtocreatethedb
structure.Veryniceindeed!Forautomaticallycreatedindices(usedtoimplementthePRIMARYKEYorUNIQUE
constraints)thesqlfieldisNULL.

COMMANDLINE
Ifyouarerunningthesqlite3commandlineprogramyoucangetahostofinformationusingthe.dumpor.schematosee
thecompletedatabaseschemaincludingalltablesandindicestablestogetalistofalltables.Typing.tableswillprovidea
completelistoftables.ThesecommandscanbefollowedbyaLIKEpatternthatwillrestrictthetablesthataredisplayed.
TheSQLITE_MASTERtablelookslikethis:
CREATE TABLE sqlite_master (
type TEXT,
name TEXT,
tbl_name TEXT,
rootpage INTEGER,
sql TEXT
);

Toviewthedatabasestructure,weneedtoconnecttothedatabasethenquerythemastertable.ToViewallthe
availableinformationwewouldusethefollowingselectstatement;
$query = "SELECT * FROM sqlite_master";

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg19 of84
SqLiteReferenceCopyright20052015

$result = $db->query("$query") or die("Error in query:

<span style='color:red;'>$query</span>");

$rows = $result->fetchAll();
echo"<pre>"; print_r($rows); echo"<pre>"; # show data

Listing:3.6Viewmasterdatabasedescriptorinformation

Array
(
[type] => table
[name] => friends
[tbl_name] => friends
[rootpage] => 2
[sql] => CREATE TABLE friends (
id INTEGER PRIMARY KEY,
name

TEXT(25),

phone TEXT(25)
)
)

Exampleoutput

Toseeboththemasterandtemp_master
$query = "SELECT * FROM sqlite_master
UNION SELECT * FROM sqlite_temp_master ";

Listing:3.7masterandtemp_masterdatadescriptors
Toseejusttabledescriptionsusethis.
$query = "SELECT sql FROM sqlite_master WHERE type='table'";
$result = $db->query("$query") or die("Error in query: <span style='color:red;'>$query</span>");
$rows = $result->fetchall(PDO::FETCH_ASSOC);
echo"<pre>"; print_r($rows); echo"<pre>"; # show data

Listing:3.8Alltabledatadescriptorinformation
Toseeaspecifictablesdescriptionusethis.
$result = $db->query("SELECT * FROM sqlite_master WHERE type='table' AND name='t1'");
$rows = $result->fetchall(PDO::FETCH_ASSOC);
echo "</pre>";

echo"<pre>"; print_r($rows); echo"<pre>"; # show data

Listing:3.9Specifictabledescriptorinformation
MultipleDatabases
The ATTACH DATABASE statement connects one or more database files to the current database
connection.
For the example below, suppose we want the current and last years sales total for one of the
employees. Each years data is arranged by employee name. We will use two db files arranged like
this

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg20 of84
SqLiteReferenceCopyright20052015

File:db1.sqlite3
Table:sales
Col1=smith
Otheremployees
50
moredata
75
moredata
moredata
moredata

File: db2.sqlite3
Table:sales
Col1=smith
Otheremployees
200
moredata
NULL
moredata
moredata

<?php
echo '<body style="font-family:arial;">';
echo '<h2>Use Multiple Database</h2>';
//

uses db1 & db2 as test databases

//

note that "main" is a reserved word for referancing the primary db

//

"SELECT * FROM t1" is the same as "SELECT main.* FROM t1"

// connect to SQLite3 database


$db = new PDO("sqlite:db1.sqlite3");
// enhanced error messages
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// query 1st database
$result = $db->query("SELECT smith FROM 'sales' WHERE 1");
$rows

= $result->fetchall(PDO::FETCH_ASSOC);

echo "<pre>"; print_r($rows); echo "</pre>";


// access second database, ATTACH needs the FULL path
$result = $db->query("ATTACH database '$_SERVER[DOCUMENT_ROOT]/astrohex_parts/db2.sqlite3' AS
lastyear");
// query 2nd database
$result = $db->query('SELECT * FROM lastyear.sales');
$rows

= $result->fetchall(PDO::FETCH_ASSOC);

echo "<pre>"; print_r($rows); echo "</pre>";


// add columns from both databases, as is required
$result = $db->query('SELECT

SUM(Total) -- SUM pulls total values

FROM (
SELECT SUM(smith) as Total FROM main.sales

-- as is required so sum can pull values

UNION
SELECT SUM(smith) as Total FROM lastyear.sales
)');
$rows

= $result->fetchall(PDO::FETCH_ASSOC);

echo "<pre>"; print_r($rows); echo "</pre>";


?>

Result
Database 1
Array (
[0] => Array
([smith] => 50.0)

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg21 of84
SqLiteReferenceCopyright20052015

[1] => Array


([smith] => 75.0)
)
Database 2
Array(
[0] => Array
([smith] => 200.0)
)
Total
Array(
[0] => Array
([SUM(Total)] => 325.0)
)

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg22 of84
SqLiteReferenceCopyright20052015

Section5
TABLE(manipulation)
AddTable
Wealreadylearnedhowtoaddatabletoadb.Sothatourreferenceiscomplete,weprovidethecodeagain.Dontforget
thatthedbconnectprocesswillcreateanewdbifitdoesnotalreadyexist.Therefore,addingatabletoanonexistent
dbwillusuallyresultinthedbandtablebeingcreatedevenifitdoesnotexist.
<?php
/* Listing 9.1 - Add table to db */
echo '<body style="font-family:arial;">';echo '<h2>Add Table</h2>';
... code to connect to database, and handle errors
#

create table
$query = "CREATE TABLE test (
id

INTEGER PRIMARY KEY,

editdate

TEXT DEFAULT (datetime('now','localtime')),

col1name

TEXT(25),

col2name

TEXT(25)

)";
$result = $db->query("$query") or die(" Error adding table: <span
style='color:red;'>$query</span>");
#

show success
echo "<i>Table added successfully.</i><br> ";

Return rows affected by last operation


$rows_affected = $result->rowCount();
echo "<span style='color:red;'>$rows_affected</span> records affected ";

close db, PHP will also do this

automatically

$db = NULL;
?>

Listing:4.1Addtabletoadatabase
Add Table
Table added successfully.
0 records affected

OUTPUTforlisting4.1

DoesTableExist
Ifweneedtocheckandseeifthetableexists,hereisanenhancedversion.
<?php
/* Listing 8.2 - Check if table exists */
echo '<body style="font-family:arial;">';
echo '<h2>Check if table exist</h2>';
... code to connect to database, and handle errors
# check master table for table name
$query = "SELECT name FROM sqlite_master WHERE type='table' and name='table_to_make'";

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg23 of84
SqLiteReferenceCopyright20052015

$db->query("$query") or die(" Error adding table: <span style='color:red;'>$query</span>");


$totaltables = sqlite_num_rows($query);
# does table exist
if ($totaltables<1) {
#

table does not exist, create table

$query = "CREATE TABLE test (


id INTEGER PRIMARY KEY,
col1name

TEXT(25),

col2name

TEXT(25)

)";

}
else{
# table exists...don't create again , do something else
}
. . . program continues

Listing:4.2Checkiftableexists

CopyTableWithData
SQLiteALTERTABLEdoesnotsupportcopytable.However,therearestillseveraloptionsavailable.
1dbmanagersmayprovidethisfeature
2tabledatacouldbeexportedtofilethenimportedunderanewtablename
3adatabasecouldbeopenedanditstablecontentscopied
4wecanuseacombinationofCREATEandSELECTtoduplicateatable
Ifavormethodfour(4).Wecantrickthedatabaseintocreatinganewtablefilledwiththecontentsofanoldtablewith
thefollowingcommand
$result = $db->query("CREATE TABLE '$newtable' AS SELECT * FROM '$oldtable'");

Listing:4.3Copytables
Hereisacompletetestprogram.
<?php
/* Listing 9.3 Copy table with data */
echo '<body style="font-family:arial;">';
echo '<h2>Copy table with data</h2>';
#

setup
$dbPath

= $_SERVER['DOCUMENT_ROOT'] . "/contacts/";

$dbFile

= "sample.sqlite3";

$oldtable = "test";
$newtable = "newtbl";
... code to connect to database, and handle errors
$result = $db->query("CREATE TABLE '$newtable' AS SELECT * FROM '$oldtable'");
$rows = $result->fetchAll();
#

show table data


$query = "SELECT * FROM '$newtable'";

$result = $db->query("$query") or die("Error in query:


style='color:red;'>$query</span>");

<span

$rows = $result->fetchall(PDO::FETCH_ASSOC);
#

show new table

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg24 of84
SqLiteReferenceCopyright20052015

foreach($rows as $array) {
echo "<pre>";
print_r($array);
echo "</pre>";
}
?>

Listing4.4Copytableanddatatonewtable

CopyTableStructure
Togetthetablestructurewecanusethefollowingcode.
<?php
/* Listing 9.4 Copy table

*/

echo '<body style="font-family:arial;">';


echo '<h2>Copy table structure</h2>';
#

setup

$dbPath

= $_SERVER['DOCUMENT_ROOT'] . "/contacts/";

$dbFile

= "sample.sqlite3";

$oldtable = "test";
$newtable = "newtbl";
... code to connect to database, and handle errors
#

get table structure

$result = $db->query("SELECT * FROM sqlite_master WHERE type='table' and name='$oldtable'");


$row = $result->fetch(SQLITE_ASSOC);
$structure = $row['sql'];
...
Listing: 9.4 Get table structure from MASTER TABLE
Next we substitute the old table name with the new table name in the structure statement using PHP
preg_replace.
#

replace old table name with new table name in the structure statement

$search

= "/CREATE TABLE $oldtable/";

$replace = "CREATE TABLE $newtable";


$string

= $structure;

$query = preg_replace($search, $replace, $string);

Listing:4.5ReplaceoldtablenamewithnewtablenameinstructurefromMASTERTABLE
Nowwecancreatethenewtablewiththesamestructure
...
#

replace old table name with new table name in the structure statement
$search

= "/CREATE TABLE $oldtable/";

$replace = "CREATE TABLE $newtable";


$string

= $structure;

$query = preg_replace($search, $replace, $string);


#

create new table

$result = $db->query("$query") or die(" Error adding table: <span


style='color:red;'>$query</span>");
...

Listing:4.6Createnewtable
<?php
/* Listing 9.4 Copy table structure */
echo '<body style="font-family:arial;">';

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg25 of84
SqLiteReferenceCopyright20052015

echo '<h2>Copy table structure</h2>';


#

setup
$dbPath

= $_SERVER['DOCUMENT_ROOT'] . "/contacts/";

$dbFile

= "sample.sqlite3";

$oldtable = "test";
$newtable = "newtbl";
... code to connect to database, and handle errors
#

get table structure


$result = $db->query("SELECT * FROM sqlite_master WHERE type='table' and name='$oldtable' ");
$row = $result->fetch(PDO::FETCH_ASSOC);
$structure = $row['sql'];

replace old table name with new table name in the structure statement
$search

= "/CREATE TABLE $oldtable/";

$replace = "CREATE TABLE $newtable";


$string

= $structure;

$query = preg_replace($search, $replace, $string);


#

create new table

$result = $db->query("$query") or die(" Error adding table: <span


style='color:red;'>$query</span>");
#

show success
echo "<i>Table added successfully.</i><br> ";

Return rows affected by last operation


$rows_affected = $result->rowCount();
echo "<span style='color:red;'>$rows_affected</span> records affected ";

close db, PHP will also do this

automatically

$db = NULL;
?>

Listing:4.7Completelistingforcopyingtablestructure

DeleteTable
Todrop(delete)atable,weusethiscommand
$query = "DROP TABLE 'test' ";

Listing:4.8Deletetable

RenameTable
Thesyntaxusedtorenameatableis
$query = "ALTER TABLE 'oldTablename' RENAME TO 'newTablename' ";

Listing:4.9Renametable
Thiscommandcannotbeusedtomoveatablebetweentwodifferentdatabases,onlytorenameatablewithinthe
samedatabase.

ViewTableStructures
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg26 of84
SqLiteReferenceCopyright20052015

Thesyntaxusedtorenameatableis
<?php
/* Listing 9.7 - View table structures */
echo '<body style="font-family:arial;">';
echo '<h2>View table structures</h2>';
#

setup

$dbPath

= $_SERVER['DOCUMENT_ROOT'] . "/contacts/";

$dbFile

= "sample.sqlite3";

... code to connect to database, and handle errors


$result = $db->query("SELECT * FROM sqlite_master WHERE type='table'"); #Lists all tables
$rows = $result->fetchall(PDO::FETCH_ASSOC);
#

print_r output
echo "<br><span style='color:red;'>Table structures for $dbFile</span>";
foreach($rows as $array) {
echo "<pre>";
print_r($array);
echo "</pre>";
}

?>

Listing:4.10Deletetable
View table structures
Table structures for sample.sqlite3
Array
(
[type] => table
[name] => test
[tbl_name] => test
[rootpage] => 2
[sql] => CREATE TABLE test (
id INTEGER PRIMARY KEY,
name

TEXT(25),

phone TEXT(25)
)
)
Array
(
[type] => table
[name] => new
[tbl_name] => new
[rootpage] => 3
[sql] => CREATE TABLE new (c1 TEXT, c2 TEXT)
)

OUTPUTForlisting4.10

TableDescription
Typefieldwillalwaysbe'table'andthenamefieldwillbethe'name'ofthetable.Togetalistofalltablesinthedatabase,
usethefollowingSELECTcommand:
SELECT name FROM sqlite_master

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg27 of84
SqLiteReferenceCopyright20052015

WHERE type='table'
ORDER BY name;

Listing:4.11tabledescriptione

Forindices,typeisequalto'index',nameisthenameoftheindex,andtbl_nameisthenameofthetabletowhichthe
indexbelongs.
Forbothtablesandindices,thesqlfieldisthetextoftheoriginalCREATETABLEorCREATEINDEXstatementthatcreated
thetableorindex.

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg28 of84
SqLiteReferenceCopyright20052015

Section6
ROW/RECORD(manipulation)
InsertRow(add)
Aswehavedonebefore,wewillputourquerystatementinavariablesothatwecanhaveabettererrormessage.

FILLINGALLFIELDS
$query = "INSERT INTO 'tablename' VALUES('col1Data','col2Data','col3Data')";
$result = $db->query("$query") or die(" Error: <span style='color:red;'>$query</span>");

Listing:5.1insertdatainsertingasinglerow(record)ofinformation.
Wedidnotspecifyanid.Becauseidisaprimaryfield,SQLiteissmartenoughtoautomaticallyincrementaunique
numberforus.
Listing5.1isashortformoftheINSERTcommandandexpectsavalueforeverycolumn(field).Ifweintendtoleavesome
columnsblankoraregoingtoeditorupdatecertaincolumnsinarow,wemustspecifywhichcolumnnameswearegoing
tobeworkingwith.
LongversionofINSERT

SELECTINGSPECIFICFIELDSTOFILL
$query = "INSERT INTO 'tablename' (field_x,field_y) VALUES('col1Data',' col2Data')";
$result = $db->query("$query") or die(" Error: <span style='color:red;'>$query</span>");

Listing:5.2insertdatacolumnnamesspecified.

InsertMultipleRows
insert into mytable (col,col2,col3)
select 'a1', 'b1', 'c1'
union
select 'a2', 'b2', 'c2'
union
select 'a3', 'b3', 'c3'
...

CopyRow
TocopyarowwefirstSELECTtherowtocopythenINSERTitasanewrow.

DeleteAllRows
Todeletealltherowsinatablewecanusethis
$query = "DELETE FROM 'tablename'";

Listing:5.3

DeleteRow(s)MatchingCondition
Ifweknowtherecordidthenwecanusethis
$query = "DELETE FROM tablename WHERE id='xxx' ";

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg29 of84
SqLiteReferenceCopyright20052015

Listing:5.4
Ifwedonotknowtherecordidthenwemustsearchfortherecordononeofitsfieldsandreturntheidforit
$query = "DELETE FROM test WHERE id=(SELECT id FROM test WHERE fieldName LIKE 'condition') ";

Listing:5.5
HereisacompleteexamplethatdeletestherecordthatstartswithanameodJames.
<?php
/* Listing 10.3 Search and delete row */
echo '<body style="font-family:arial;">';
echo '<h2>Search and delete row</h2>';
... code to connect to database, and handle errors
#

delete row
$query = "DELETE FROM test WHERE id=(SELECT id FROM test WHERE name LIKE 'James%') ";

$result = $db->query("$query") or die(" Error deleting row: <span


style='color:red;'>$query</span>");
#

show success
echo "<i>Row deleted successfully.</i><br> ";

Return rows affected by last operation


$rows_affected = $result->rowCount();
echo "<span style='color:red;'>$rows_affected</span> records affected ";

close db, PHP will also do this

automatically

$db = NULL;
?>

Listing:5.6Searchanddeletearow
Delete row
Row deleted successfully.
1 records affected

OUTPUTresultofrunninglisting:5.6

UpdateRow(s)MatchingCondition
Forindices,typeisequalto'index',nameisthenameoftheindex,andtbl_nameisthenameofthetabletowhichthe
indexbelongs.,usethefollowingSELECTcommand:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Listing:5.8
Anotherwaytoupdateistomatchastringandreplace,
UPDATE table_name
SET field=replace(field, 'george', 'George')
WHERE zip LIKE '%99123%'

Toreplaceallnewlinecharactersfromafield(x'0a'isalsoused),
UPDATE table_name
SET field=replace(field, x'0d', '')
WHERE condition

Listing:5.8
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg30 of84
SqLiteReferenceCopyright20052015

SQLUPDATEWARNING
Becarefulwhenupdatingrecords.IfwehadomittedtheWHEREclausethenALLrowswillbeupdated,likethis:
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'

Listing:5.8
Forbothtablesandindices,thesqlfieldisthetextoftheoriginalCREATETABLEorCREATEINDEXstatementthatcreated
thetableorindex.

CountRows
ThereisnowayforPDOtoknowtherowCountofaSELECTresultbecausetheSQLiteAPIitselfdoesn'tofferthisability.
ThereforerowCont()doesnotwork.WecancountcolumnsusingPDOsbuiltincolumnCount()function.Hereishowto
getthesecounts.
1.

UsePDO'sfetch_all()functiontofetchalltherowsintoanarray,thenusecount()onit.

2.

DoanextraquerytoSELECTCOUNT(*).
$query = "SELECT * FROM 'tablename'";
$result = $db->query("$query")
or die("Error counting rows: <span style='color:red;'>$query</span>");
$rowcount = count($result);
echo "Total rows = $rowcount<br>";
$query = "SELECT * FROM 'tablename'";
$result = $db->query("$query")
or die("Error counting rows: <span style='color:red;'>$query</span>");
$rowcount = count($result->fetchAll());
echo "Total rows = $rowcount<br>";
$query = "SELECT COUNT(*) FROM 'tablename'";
$result = $db->query("$query")
or die("Error counting rows: <span style='color:red;'>$query</span>");
$rows = $result->fetchAll();
$rowcount = $rows[0][0];
echo "Total rows = $rowcount<br>";

CountColumns
$query = "SELECT * FROM 'tablename'";
$result = $db->query("$query")
or die("Error counting rows: <span style='color:red;'>$query</span>");
$colcount = $result->columnCount();
echo "Column count = $colcount<br>";

Listing:5.7Countrowsandcolumns

IndexDescription
Forindices,typeisequalto'index',nameisthenameoftheindex,andtbl_nameisthenameofthetabletowhichthe
indexbelongs.,usethefollowingSELECTcommand:
SELECT name FROM sqlite_master
WHERE type='index'

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg31 of84
SqLiteReferenceCopyright20052015

ORDER BY name;

Listing:5.8
Forbothtablesandindices,thesqlfieldisthetextoftheoriginalCREATETABLEorCREATEINDEXstatementthatcreated
thetableorindex.

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg32 of84
SqLiteReferenceCopyright20052015

Section7
COLUMN/FIELD(manipulation)
AddColumn
$query = "ALTER TABLE '[database.]tablename' ADD COLUMN 'newColumn' TEXT ";

Listing:6.1Creatinganewdatabase

CopyColumnanddata
SQLiteALTERTABLEonlysupportsaddcolumntotheendofatable,orchangetablename.Ifyouwanttomakeother
changesthanthetablewillhavetobecopiedintheproperorderandrenamed.
$result = $db->query("CREATE TABLE '$newtable' AS SELECT

'colToCopy ' FROM '$oldtable'");

Listing:6.2copyacolumntoanewtable

DeleteColumn
Suppose you have a table named "t1" with columns names "a", "b", and "c". If you want to delete
column "c" from this table, than the following steps illustrate how this could be done:
CREATE TEMPORARY TABLE t1_backup(a,b);
INSERT INTO t1_backup SELECT a,b FROM t1;
DROP TABLE t1;
CREATE TABLE t1(a,b);
INSERT INTO t1 SELECT a,b FROM t1_backup;
DROP TABLE t1_backup;

Listing:6.3Creatinganewdatabase

RenameColumn
Sayyouhaveatableandneedtorename"old_b"to"new_b":
1) Rename the old table:
ALTER TABLE orig_table_name RENAME TO tmp_table_name;
2) Create a new table, based on the old table but with the updated column name:
CREATE TABLE orig_table_name (
col_a INT,
new_b INT
);
3) Copy the contents across from the original table.
INSERT INTO orig_table_name(col_a, new_b)
SELECT col_a, old_b
FROM tmp_table_name;
4) Drop the old table.
DROP TABLE tmp_table_name;

Listing:6.4Creatinganewdatabase

CountColumns
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg33 of84
SqLiteReferenceCopyright20052015

WecancountcolumnsusingPDOsbuiltincolumnCount()function.ThereisnowayforPDO
toknowtherowCountofaSELECTresultbecausetheSQLiteAPIitselfdoesn'tofferthis
ability.ThereforerowCont()doesnotwork.Hereishowtogetthesecounts.

$rowcount = count($result->fetchAll());
echo "Total rows = $rowcount<br>";
$colcount = $result->columnCount();
echo "Column count = $colcount<br>";

Listing:6.5Countrowsandcolumns

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg34 of84
SqLiteReferenceCopyright20052015

Section8
SEARCHES/SHOW(manipulation)
SimpleSelectSyntax
Recallfromsection5thatwecansearchourdatabaseusingSELECTthenextracttheinformationusingFETCH.Thesimple
formofthiscommandisshownbelow.
$query = "SELECT <column(s)> FROM 'table' ";
$result = $db->query($query, PDO::FETCH_ASSOC);
$row = $result->fetchall(PDO::FETCH_ASSOC);

Listing:7.1SimplesearchesusingSELECT
Weoftenuseanasterisk*forthecolumninformationsothatallcolumnsintherow(s)arereturned.
$query = "SELECT * FROM 'table' ";

Listing:7.2GenericformofSELECT

Thefourfetchtypes
/* PDOStatement::fetch styles */
$query = "select * from t1";
print("<br><br>PDO::FETCH_ASSOC: next row as an array indexed by column name.<br>");
$result = $db->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC);
echo "<pre>"; print_r($row); echo "</pre>";
print("<br><br>");
print("PDO::FETCH_BOTH: next row as an array indexed by both column name and number<br>");
$result = $db->query($query);
$row = $result->fetch(PDO::FETCH_BOTH);
echo "<pre>"; print_r($row); echo "</pre>";
print("<br><br>");
print("PDO::FETCH_LAZY: next row as an anonymous object with column names as properties<br>");
$result = $db->query($query, PDO::FETCH_LAZY);
$row = $result->fetch(PDO::FETCH_LAZY);
echo "<pre>"; print_r($row); echo "</pre>";
print("<br><br>");
print("PDO::FETCH_OBJ: next row as an anonymous object with column names as properties<br>");
$result = $db->query($query, PDO::FETCH_OBJ);
$row = $result->fetch(PDO::FETCH_OBJ);
echo "<pre>"; print_r($row); echo "</pre>";
print("<br><br>");

Listing:7.3
Resultsfromtheabovelisting
PDO::FETCH_ASSOC: next row as an array indexed by column name.
Array
(
[id] => 1
[name] => Frank
[dob] => 2011.12.09

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg35 of84
SqLiteReferenceCopyright20052015

PDO::FETCH_BOTH: next row as an array indexed by both column name and number
Array
(
[id] => 1
[0] => 1
[name] => Frank
[1] => Frank
[dob] => 2011.12.09
[2] => 2011.12.09
)

PDO::FETCH_LAZY: next row as an anonymous object with column names as properties PDORow Object
(
[queryString] => select * from t1
[id] => 1
[name] => Frank
[dob] => 2011.12.09
)

PDO::FETCH_OBJ: next row as an anonymous object with column names as properties stdClass Object
(
[id] => 1
[name] => Frank
[dob] => 2011.12.09
)

WHERE
TheWHEREclauseincludesacomparisonpredicate,whichrestrictstherowsreturnedbythequery.TheWHEREclause
eliminatesallrowsfromtheresultsetforwhichthecomparisonpredicatedoesnotevaluatetoTrue.Rememberthatif
weusetheWHEREstatementbyitself,itrequiresanexactmatch.
$query = "SELECT * FROM 'table' WHERE name='James Bond' ";
or
$query = "SELECT * FROM 'table' WHERE name='$lname' "; // must use ' ticks with vars

Listing:7.4SimplesearchesusingWHERE
IfwewanttousewildcardsthenwemustaddtheLIKEstatement.WhenusingLIKE,wehavethefollowingrules:

_
=
%
=
unix)

under score _ will match any single character (like the ? in batch files, dos, or unix)
percent % will match zero or more of any character (like the * in batch files, dos, or

SHOWRECORDONSINGLELINE
# show each record on single line
$result = $db->query("SELECT * FROM 'table' WHERE 1 ");
$rows = $result->fetchall(PDO::FETCH_ASSOC);

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg36 of84
SqLiteReferenceCopyright20052015

foreach($rows as $row) {
$record = implode(' | ',$row);
echo "$record<br>";
}

LIKE
TheLIKEclauseallowsusetousewildcardsorlessspecificmatchcriteria
Wecanalsousemorethanonecondition.
$query = "SELECT * FROM 'table' WHERE name LIKE 'James%'";

Listing:7.5SimplesearchesusingLIKE

AND
WecanuseANDtorequiremorethanonecondition.Considerthisexample
$query = "SELECT * FROM 'table' WHERE name LIKE 'James%' AND WHERE phone LIKE '007%' ";

Listing:7.6SimplesearchesusingANDformultipleconditions

OR
WealsocoulduseORtoselectbetweendifferentconditions.Considerthisexample
$query = "SELECT * FROM 'table' WHERE name LIKE 'James%' OR WHERE name LIKE 'Jane%' ";

Listing:7.7SimplesearchesusingANDformultipleconditions
Wehaveseveralotheroptionsandthatleadsustooursectiononadvancedsearches.

AdvancedSelectSyntax
LIMIT
Whatifweneedasetofrowsfromagivenoffsetsuchasthenthrecord?WecanusetheLIMITstatementtodrawresults
startingwithagivenindexandgetthespecifiednumberofrowsfromthatpoint.Thesyntaxis
LIMIT index, count

Hereisatypicalexamplewherewewantthethirdrecordfromthematchset
$query = "SELECT * FROM 'tablename' LIMIT 2,1";

Listing:7.8
Thisreturnsthethirdrecordbecauseeweusedanindexof2andindexesstartwithzero(0,1,2)Wewillget1record
backbecausewegavearecordcountof1.Ifwewantedthefirst5recordsafter100thenwewoulduseLIMIT99,5.
TherearetwoverycommonusesforLIMIT.Thefirstistoshowareasonablenumberofrecordsonthescreenorprinter
page.Ifweweregoingtolist100recordsfromacertaindate,wemightwanthalfofthemonthefirstpageandtheother
halfprintedonthesecondpage.
Ourstatementsmightlooksomethinglikethis
$query = "SELECT * FROM 'tablename' WHERE 'dob'='1975' LIMIT 0, 49";

Listing:7.9
Ournextquerywouldbe
$query = "SELECT * FROM 'tablename' WHERE 'dob'='1975' LIMIT 50, 50";

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg37 of84
SqLiteReferenceCopyright20052015

Listing:7.10
Theothercommonuseoflimitistogetthepreviousornextrecordfromthecurrentone.Ifweareatindex65,wecan
addorsubtract1fromthisindexandgetarecordineitherdirection.
# get next record
$rowindex = 65;
$query = "SELECT * FROM 'tablename' LIMIT ($rowindex+1), 1";
# more...code
# get previous record
$rowindex = 65;
$query = "SELECT * FROM 'tablename' LIMIT ($rowindex-1), 1";

Listing:7.11
WecoulduseLIMIT$rowindex+1,1butIthinkthe()makesthecodemorereadablesoIuseLIMIT($rowindex+1),1.Of
coursewecanhavemorethanonerowreturnedbyusingdifferentvaluesforcount.

ORDERBY
TheORDER BYclauseidentifieswhichcolumnsareusedtosorttheresultingdata,andinwhichdirectiontheyshouldbe
sorted(optionsareascendingordescending).WithoutanORDER BYclause,theorderofrowsreturnedbyanSQLquery
usuallycorrelatestotheprimarykeyfieldsuchasanIDnumber.
Thesyntaxis
ORDER BY column
or
ORDER BY column DIRECTION

Considerthisexample

# sort records by last name in DESCENDING order


$query = "SELECT * FROM 'tablename' ORDER BY 'lname''DESC';
# more...code
# sort records by last name in ASCENDING order (default)
$query = "SELECT * FROM 'tablename' ORDER BY 'lname''ASC';

Listing:7.12
Ifnosortorderisspecified,itwillbeASCENDINGwhichisalphabeticaland/orsmalltolargenumbers.Toreversethe
defaultsortorderwemustuseDESC.Wecanusemorethanonecolumnidthereisamatch.Forexamplesupposewe
aresortingstudentnamesinaschoolandthereismorethanoneSmith.Wecanusethedateofbirthtoo

# sort records by last name in ASCENDING order (default)


$query = "SELECT * FROM 'tablename' ORDER BY 'lname''DESC','dob''ASC';

Listing:7.13
Thissortsthelastnamesalphabetically(normalorder),butthe'dob''ASC'liststhestudentswiththesamename;oldestto
youngestaccordingtodateofbirth(oppositethenormalorder).

GROUPBY
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg38 of84
SqLiteReferenceCopyright20052015

Onlyshowsfieldsexplicitlymentioned.Whentherecordsaregrouped,allfieldsexceptthosewhichareexplicitlygivenin
GROUPBYareremoved.TheGROUP BYclauseisusedtoprojectrowshavingcommonvaluesintoasmallersetofrows.
GROUP BYisoftenusedinconjunctionwithSQLaggregationfunctionsortoeliminateduplicaterowsfromaresultset.
TheWHEREclauseisappliedbeforetheGROUP BYclause.

HAVING
TheHAVINGclauseincludesapredicateusedtofilterrowsresultingfromtheGROUP BYclause.Becauseitactsonthe
resultsoftheGROUP BYclause,aggregationfunctionscanbeusedintheHAVINGclausepredicate.AHAVINGclausein
SQLspecifiesthatanSQLSELECTstatementshouldonlyreturnrowswhereaggregatevaluesmeetthespecified
conditions.ItwasaddedtotheSQLlanguagebecausetheWHEREkeywordcouldnotbeusedwithaggregatefunctions
ToreturnalistofdepartmentIDswhosetotalsalesexceeded$1000onthedateofJanuary1,2000,alongwiththesumof
theirsalesonthatdate:

SELECT DeptID, SUM(SaleAmount)


FROM Sales
WHERE SaleDate = '01-Jan-2000'
GROUP BY DeptID
HAVING SUM(SaleAmount) > 1000

Listing:7.14
Thefollowingquerywillreturnthelistofdepartmentswhohavemorethan1employee:
SELECT DepartmentName, COUNT(*)
FROM employee,department
WHERE employee.DepartmentID = department.DepartmentID
GROUP BY DepartmentName
HAVING COUNT(*)>1;

Listing:7.15

DISTINCT
Ifdataisduplicated,returnsonlyonecopy.
SELECT distinct f1 FROM t1 WHERE f1=condition

IfwehadTABLEofnamesandfieldslikethis.
id
1
2
3
4

fname
Mickey
Donald
Mini
Might

lname
Mouse
Duck
Mouse
Mouse

SELECT distinct lname FROM names WHERE 1

RESULT: Mouse, Duck

FINDINGDUPLICATES
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg39 of84
SqLiteReferenceCopyright20052015

WiththeSQLstatementbelowyoucanfindduplicatevaluesinanytable,justchangethetablefieldintothecolumnyou
wanttosearchandchangethetableintothenameofthetableyouneedtosearch.

This will show the duplicated record


SELECT *
FROM table
GROUP BY field
HAVING (COUNT( field ) > 1)

Thisshowstablefieldandhowmanytimesitisfoundasaduplicate.
SELECT
tablefield, COUNT(tablefield) AS dup_count
FROM
table
GROUP BY tablefield
HAVING
(COUNT(tablefield) > 1)

Afastermethodis
SELECT t1.*
FROM table AS t1
LEFT JOIN table AS t2
ON t1.id != t2.id
AND t1.field = t2.field
WHERE t2.id IS NOT NULL
GROUP BY t1.id

Somefurthertemperingwiththestatementgetsthecompleterecordsthataredoubled.

SELECT *
FROM table
WHERE tablefield IN (
SELECT tablefield
FROM table
GROUP BY tablefield
HAVING (COUNT(tablefield ) > 1)
)

DELETEINGDUPLICATES
delete from MyTable
where exists (select * from MyTable t2 where t2.field = MyTable.field and t2.id < MyTable.id)

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg40 of84
SqLiteReferenceCopyright20052015

Section9
Debug&Errors
ErrorCodes
TheerrorcodesforSQLiteversion3areunchangedfromversion2.
Theyareasfollows:
OK0Successfulresult
ERROR1SQLerrorormissingdatabase
INTERNAL2AninternallogicerrorinSQLite
PERM3Accesspermissiondenied
ABORT4Callbackroutinerequestedanabort
BUSY5Thedatabasefileislocked
LOCKED6Atableinthedatabaseislocked
NOMEM7Amalloc()failed
READONLY8Attempttowriteareadonlydatabase
INTERRUPT9Operationterminatedbysqlite_interrupt()
IOERR10SomekindofdiskI/Oerroroccurred
CORRUPT11Thedatabasediskimageismalformed
NOTFOUND12(InternalOnly)Tableorrecordnotfound
FULL13Insertionfailedbecausedatabaseisfull
CANTOPEN14Unabletoopenthedatabasefile
PROTOCOL15Databaselockprotocolerror
EMPTY16(InternalOnly)Databasetableisempty
SCHEMA17Thedatabaseschemachanged
TOOBIG18Toomuchdataforonerowofatable
CONSTRAINT19Abortduetoconstraintviolation
MISMATCH20Datatypemismatch
MISUSE21Libraryusedincorrectly
NOLFS22UsesOSfeaturesnotsupportedonhost
AUTH23Authorizationdenied
ROW100sqlite_step()hasanotherrowready
DONE101sqlite_step()hasfinishedexecuting

1)Ifyoucopiedcodefromapageofthisreference
IfyoucopiedandpastedcodefromthisMSWorddocument.Beforewarnedthatittransposesstraightticks('),
apostrophes,andquotes("")intoforwardandreverseversionswhichareincompatiblewiththePHPparser.Ihave
madeanattempttoremoveasmanyaspossible,butafewmaylinger.
Afullsetofprovenroutinesshouldhaveaccompaniedthisdocument.

2)SomeSQLiteversionshaveincompatibilities
NOTE:Databasesareunsupportedbetween3.1.xand3.2.xversionsofSQLite.

file_format1Version3.0.0.
file_format2Version3.1.3.
file_format3Version3.1.4.

Version3.0canonlyusefileswithfile_format1.
Version3.1.3canreadandwritefileswithfile_format1orfile_format2.
Version3.1.4canreadandwritefileformats1,2and3.

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg41 of84
SqLiteReferenceCopyright20052015

Atypicalerrorissomethinglikethis,"malformeddatabaseschemaunabletoopenadatabasefile

3)"Invalidresource"error
Ifyougetanerrorreporting"invalidresource"whenattemptingaqueryonadatabasetableandloopingthroughit,
theversionoftheSQLiteextensioncompiledintoPHPmightbeincompatiblewiththeversionthatwasusedto
createthedatabase(likeSQLite2.xvs3.x).

Thedatabasemightopen(connect)ok,butwillfailwhenquerying.

$db=newPDO('sqlite:/tmp/foo.db');//success
foreach($db>query('SELECT*FROMbar')as$row)//printsinvalidresource

4)Sensitivitytowhitespace
Incertaincircumstanceswhitespacecancauseerrors,becareful!
Correct ->

$db = new PDO("sqlite:$dbPath$dbFile");

Error

$db = new PDO("sqlite: $dbPath$dbFile");

->

Correct ->

$db = new PDO("sqlite:$dbPath$dbFile");

Error

$db = new PDO("sqlite:$dbPath$dbFile ");

->

Correct ->

")

Error

" )

->

5)unabletoopenfile
Ifyoureceiveanerrorwhiletryingtowritetoasqlitedatabase(update,delete,drop):
Warning: PDO::query() [function.query]: SQLSTATE[HY000]: General error: 1 unable to open database.

Aunixsystemmayhavefolderorfilepermissionproblems.Thefoldercontainingthedatabasefilemustbewriteable.

6)SQLITE_CORRUPTerror
AnSQLITE_CORRUPTerrorisreturnedwhenSQLitedetectsanerrorinthestructure,format,orothercontrolelementsof
thedatabasefile.YourcanusePRAGMAintegrity_checktodoathoroughanintensivetestofthedatabaseintegrityor
youcanusePRAGMAquick_checktodoafasterbutlessthoroughtestofthedatabaseintegrity.

7)WHEREClauseerror
TheSQLstandardrequiressinglequotes,notdoublequotes,aroundstringliterals.AWHEREclauseexpressionshould
read:column1='column2'notcolumn1=column2.

8)Unexpectedreturnvalue,i.e.Array
Afterqueryusingsomethingsimilarto
$result = $db->query("SELECT * FROM 'test'");
$rows = $result->fetchAll();
echo "rows = $rows";

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg42 of84
SqLiteReferenceCopyright20052015

echoshows
Array

Theresultarrayhasnotbeenfullyprocessed.Inotherwords,theresultisanarrayandneedstobeaccessedusingindex
valuessuchasforeach($rowsas$row)clauseor$var=$rows[xx].

9)SYNTAXERROR,UnexpectedEnd
Abracketismissingfromafornextorforeachconstruct
foreach($rows as $row){
do something...;
missing closing }

10)unexpectedT_VARIABLE
Thiserrorusuallyindicatesasyntaxerror.Themostcommoncausesare
missing;inapreviousline
matchingcharacterpairsmissing,i.e,,[,{,(etc.

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg43 of84
SqLiteReferenceCopyright20052015

Section10
VIEWS(custom)
Aviewisaspecificlookondatainfromoneormoretables.Itcanarrangedatainsomespecificorder,higlightorhide
somedata.Aviewconsistsofastoredqueryaccessibleasavirtualtablecomposedoftheresultsetofaquery.Unlike
ordinarytablesaviewdoesnotformpartofthephysicalschema.Itisadynamic,virtualtablecomputedorcollatedfrom
datainthedatabase.
Inthenextexample,wecreateasimpleview.
sqlite> SELECT * FROM Cars;

Listing:8.1
Id

Name

Cost

----------

----------

----------

Audi

52642

Mercedes

57127

Skoda

9000

Volvo

29000

Bentley

350000

Citroen

21000

Hummer

41400

Volkswagen

21600

Output:8.1
Thisisourdata,uponwhichwecreatetheview.

sqlite> CREATE VIEW CheapCars AS SELECT Name FROM Cars WHERE Cost < 30000;
sqlite> SELECT * FROM CheapCars;

Listing:8.2
Name
---------Skoda
Volvo
Citroen
Volkswagen

Output:8.2
Technicallyaviewisavirtualtable.Sowecanlistallviewswitha.tablescommand.Toremoveaview,weusetheDROP
VIEWSQLstatement.
sqlite> .tables
Books

CheapCars

Friends

Names

Reservations

Cars

Customers

Log

Orders

Testing

Testing

sqlite> DROP VIEW CheapCars;


sqlite> .tables
Books

Customers

Log

Orders

Cars

Friends

Names

Reservations

EndOfSection
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg44 of84
SqLiteReferenceCopyright20052015

Section11
TRIGGERS(manipulation)
Triggersaredatabaseoperationsthatareautomaticallyperformedwhenaspecifieddatabaseeventoccurs.

InsertRowTimestamp
Itisagoodpracticetokeeptractofthelasttimeafilewasedited.Wedothisbysavingatimestamp.Aninserttriggeris
createdbelowinthefile"trigger1".TheCoordinatedUniversalTime(UTC)willbeenteredintothefield"timeEnter",and
thistriggerwillfireafterarowhasbeeninsertedintothetablet1.
-- ********************************************************************
--

Creating a trigger for timeEnter

--

Run as follows:

--

$ sqlite3 test.db < trigger1

-- ********************************************************************
CREATE TRIGGER update_editdate AFTER INSERT ON t1
BEGIN
UPDATE t1 SET editdate = DATETIME('NOW')

WHERE rowid = new.rowid;

END;
-- ********************************************************************

Listing:9.1
Anotherwayofkeepingatimestamp(perhapseasierthanatrigger)istousethedefaultvalueofthetablescheme.The
fielddefinitionisgivenbelow.
editdate

DATETIME DEFAULT (datetime('now','localtime')),

Listing:15.2Timestampusingdefaultcolumntext

LoggingAllInserts,Updates,andDeletes
Thescriptbelowcreatesthetableexamlogandthreetriggers(update_examlog,insert_examlog,anddelete_examlog)to
recordupdates,inserts,anddeletesmadetotheexamtable.Inotherwords,wheneverachangeismadetotheexam
table,thechangeswillberecordedintheexamlogtable,includingtheoldvalueandthenewvalue.Ifyouarefamiliar
withMySQL,thefunctionalityofthislogtableissimilartoMySQL'sbinlog.SeeTips2,24,and25ifyouwouldlikemore
informationonMySQL'slogfile.
--

Create an update trigger

CREATE TRIGGER update_examlog AFTER UPDATE ON exam


BEGIN
INSERT INTO examlog

(ekey,ekeyOLD,fnOLD,fnNEW,lnOLD,
lnNEW,examOLD,examNEW,scoreOLD,
scoreNEW,sqlAction,examtimeEnter,
examtimeUpdate,timeEnter)

values (new.ekey,old.ekey,old.fn,new.fn,old.ln,
new.ln,old.exam, new.exam,old.score,
new.score, 'UPDATE',old.timeEnter,
DATETIME('NOW'),DATETIME('NOW') );
END;
---

Also create an insert trigger

--

NOTE

AFTER keyword ------v

CREATE TRIGGER insert_examlog AFTER INSERT ON exam


BEGIN

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg45 of84
SqLiteReferenceCopyright20052015

INSERT INTO examlog

(ekey,fnNEW,lnNEW,examNEW,scoreNEW,
sqlAction,examtimeEnter,timeEnter)

values (new.ekey,new.fn,new.ln,new.exam,new.score,
'INSERT',new.timeEnter,DATETIME('NOW') );
END;
--

Also create a DELETE trigger

CREATE TRIGGER delete_examlog DELETE ON exam


BEGIN
INSERT INTO examlog

(ekey,fnOLD,lnNEW,examOLD,scoreOLD,
sqlAction,timeEnter)

values (old.ekey,old.fn,old.ln,old.exam,old.score,
'DELETE',DATETIME('NOW') );
END;

Listing:9.2
Inthefollowingexample,wewillusetheFriendstableandcreateanewLogtable.
CREATE TABLE Log(Id integer PRIMARY KEY, OldName text, NewName text, Date text);

Listing:9.3
Wewillcreate2newtablesforthenextexamplewithtriggers.
CREATE TRIGGER mytrigger UPDATE OF Name ON Friends
BEGIN
INSERT INTO Log(OldName, NewName, Date) VALUES(old.Name, new.Name, datetime('now'));
END;

Listing:9.4
WecreateatriggercalledmytriggerwiththeCREATETRIGGERstatement.ThistriggerwilllaunchaINSERTstatement
wheneverweupdatethenamecolumnoftheFriendstable.TheINSERTstatementwillinserttheoldname,thenew
nameandthetimestampintotheLogtable.
sqlite> SELECT * FROM Friends;
Id

Name

Sex

---------1
2
3
4
5
6
7

---------Jane
Thomas
Franklin
Elisabeth
Mary
Lucy
Jack

---------F
M
M
F
F
F
M

Thisisourdata.
Next,wearegoingtoupdateonerowoftheFriendstable.
sqlite> UPDATE Friends SET Name='Frank' WHERE Id=3;

Listing:9.5
Weupdatethethirdrowofthetable.Thetriggerislaunched.
sqlite> SELECT * FROM Log;
Id

OldName

NewName

Date

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg46 of84
SqLiteReferenceCopyright20052015

----------

----------

----------

-------------------

Franklin

Frank

2009-11-14 16:36:28

WechecktheLogtable.Thislogconfirmstheupdateoperationweperformed.

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg47 of84
SqLiteReferenceCopyright20052015

Section12
TRANSACTIONS
Atransactionisanatomicunitofdatabaseoperationsagainstthedatainoneormoredatabases.Theeffectsofallthe
SQLstatementsinatransactioncanbeeitherallcommittedtothedatabaseorallrolledback.
InSQLite,anycommandotherthantheSELECTwillstartanimplicittransaction.Manualtransactionsarestartedwiththe
BEGINTRANSACTIONstatementandfinishedwiththeCOMMITORROLLBACKstatements.
BEGIN TRANSACTION;
CREATE TABLE Test(Id integer NOT NULL);
INSERT INTO Test VALUES(1);
INSERT INTO Test VALUES(2);
INSERT INTO Test VALUES(3);
INSERT INTO Test VALUES(NULL);
COMMIT;

Listing:10.1
WehaveaNOTNULLconstraintsetontheIdcolumn.Thus,thefourthinsertwillnotsucceed.SQLitedoestransactions
specifically.Forsomeerrors,itrevertsallchanges.Forothers,itrevertsonlythelaststatementandleavesotherchanges
intact.Inourcase,thetableiscreatedandthefirstthreeinsertsarewrittenintothetable.Thefourthoneisnot.
Say,wealreadyhadanemptytablenamedTest.Executingtheabovetransactionwouldfailcompletely.Nochanges
wouldbewritten.IfwechangedtheCREATETABLEstatementintoCREATETABLEIFNOTEXISTS,thefirstthree
statementswouldexecute.
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS Test(Id integer NOT NULL);
INSERT INTO Test VALUES(1);
INSERT INTO Test VALUES(2);
INSERT INTO Test VALUES(3);
INSERT INTO Test VALUES(NULL);
ROLLBACK;

Listing:10.2
AtransactioncanendwithaCOMMIToraROLLBACKstatement.TheROLLBACKrevertsallchanges.

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg48 of84
SqLiteReferenceCopyright20052015

Section13
JOINS
JOIN:

Combinedatafromtwoormoretables

INNERJOIN:

DefaultJointype.Createnewtablewhereoneormoretablerowsmeetcriteria.

NATURALJOIN:

Combinesallcolumnsintableswithsamecolumnname.

LEFTOUTERJOIN:

Retainallrecordsintableontheleftside(regardlessofmatch),mergeonlymatchesfromright
side.

RIGHTOUTERJOIN:

Retainallrecordsintableontherightside(regardlessofmatch),mergeonlymatchesfromleft
side.
Note: LeftandrightJoinrefertothetwosidesoftheJOINkeyword.LeftandRIGHTJoinsare
identicalbyreversingtablepositions.

FULLJOIN:

Mergealltablesregardlessofmatch.

SELFJOIN:

Searchonetableformatchesinacolumnwithtwooremoreidenticalentries.i.e.Samedept
nameexcludessingleentries.

CROSSJOIN:

Getsarecordfromthefirsttableandthencreatesanewrowforeveryrowinthe2ndtable.It
thendoesthesameforthenextrecordinthefirsttableetc.Cautionshouldbeused,when
thereisnoWHEREfilterappliedthenumberofrecordsreturnedwillbeT1*T2records.

MERGEROW:
UNION:

Concatenatesfielddataagainstmatchcolumn
TheUNIONoperatorisusedtocombinetheresultsetoftwoormoreSELECTstatements.

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg49 of84
SqLiteReferenceCopyright20052015

Supposewehavethefollowingtables
sqlite> .headers ON
sqlite> SELECT * FROM Artists;
ArtistID|ArtistName
1
|Peter Gabriel
2
|Bruce Hornsby
3
|Lyle Lovett
4
|Beach Boys
5
|Supernatural
sqlite> SELECT * FROM CDs;
CDID|ArtistID|Title
|Date
1
|1
|So
|1984
2
|1
|Us
|1992
3
|2
|The Way It Is
|1986
4
|2
|Scenes from the Southside|1990
5
|1
|Security
|1990
6
|3
|Joshua Judges Ruth |1992
7
|4
|Pet Sounds
|1966

CROSSJOIN
Itisalsocalledthe"directjoin"orCartesianproduct:
sqlite>SELECT * FROM Artists, CDs;

Listing:11.1
InsomeSQLdialectitcanbealsoused
sqlite>SELECT * FROM Artists CROSS JOIN CDs;

Listing:11.2
LetustrytofiltertheresultwiththeWHEREclause:
sqlite>SELECT ArtistName, Title FROM Artists, CDs WHERE Artists.ArtistID=CDs.ArtistID;

Listing:11.3
Itgives
Peter Gabriel|So
Peter Gabriel|Us
Peter Gabriel|Security
Bruce Hornsby|The Way It Is
Bruce Hornsby|Scenes from the Southside
Lyle Lovett |Joshua Judges Ruth
Beach Boys
|Pet Sounds

Toavoidconfusion,usethisstatementinstead
sqlite>SELECT Artists.ArtistName, CDs.Title FROM Artists, CDs WHERE Artists.ArtistID=CDs.ArtistID;
or with aliases
sqlite>SELECT a.ArtistName, c.Title FROM Artists a, CDs c WHERE a.ArtistID=c.ArtistID;

Listing:11.4
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg50 of84
SqLiteReferenceCopyright20052015


INNERJOIN
ThesameresultcanbeachievedwiththeINNERJOINclause:
sqlite> SELECT Artists.ArtistName, CDs.Title FROM Artists INNER JOIN CDs ON
Artists.ArtistID=CDs.ArtistID;

Listing:11.5
TheINNERJOINreturnsallrowsfrombothtableswherethereisamatch.IftherearerowsinArtiststhatdonothave
matchesinCDs,thoserowswillnotbelisted.

LEFTOUTERJOIN
TheLEFTOUTERJOINoperatorensuresthatallrowsonthe"left"sideofthejoin,inthiscasetheArtiststable,willbe
included.
sqlite>SELECT * FROM Artists LEFT OUTER JOIN CDs ON Artists.ArtistID = CDs.ArtistID;

Listing:11.6
ThereisnoSupernaturalinCDsbutyoucanstillseeSupernaturalwithemptyfieldsfromArtists:
ArtistID|ArtistName
|CDID|ArtistID|Title
|Date
1
|Peter Gabriel|1
|1
|So
|1984
1
|Peter Gabriel|2
|1
|Us
|1992
1
|Peter Gabriel|5
|1
|Security
|1990
2
|Bruce Hornsby|3
|2
|The Way It Is
|1986
2
|Bruce Hornsby|4
|2
|Scenes from the Southside|1990
3
|Lyle Lovett |6
|3
|Joshua Judges Ruth |1992
4
|Beach Boys
|7
|4
|Pet Sounds
|1966
5
|Supernatural |
|
|
|

SomeSQLdialectsuseLEFTJOIN.
Inotherdialects(Oracle)insteadof
sqlite> SELECT Artists.ArtistName, CDs.Title
------> FROM Artists
------> LEFT OUTER JOIN CDs
------> ON Artists.ArtistID = CDs.ArtistID;

Listing:11.7
thefollowingstatementisused
SELECT Artists.ArtistName, CDs.Title
FROM Artists, CDs
WHERE Artists.ArtistID = CDs.ArtistID(+)

Listing:11.8
The(+)symboldenotesthetable(side)thatmayhavenomatchingrowstotheothertable(side).Thinkofthisas
everythingfromtheleftplusmatchingvaluesfromtheright.
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg51 of84
SqLiteReferenceCopyright20052015

RIGHTOUTERJOINandFULLOUTERJOIN
SimilarlythisSQL
SELECT Artists.ArtistName, CDs.Title
FROM Artists
RIGHT OUTER JOIN CDs
ON Artists.ArtistID = CDs.ArtistID;

Listing:11.9
Or
SELECT Artists.ArtistName, CDs.Title
FROM Artists, CDs
WHERE Artists.ArtistID(+) = CDs.ArtistID

Listing:11.10
wouldreturnallrecordsfromtherightside.
CurrentlySQLitesupportsneitheroftheabovesyntax.Howeverthereiseasyworkaround:useLEFTOUTERJOINwith
interchangedtables.TheFULLOUTERJOINclauseisnotsupportedaswell.

UNION
TheUNIONoperatorisusedtocombinetheresultsetoftwoormoreSELECTstatements.
NoticethateachSELECTstatementwithintheUNIONmusthavethesamenumberofcolumns.Thecolumnsmustalso
havesimilardatatypes.Also,thecolumnsineachSELECTstatementmustbeinthesameorder.
SQLUNIONSyntax
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

Listing:11.11
Note:TheUNIONoperatorselectsonlydistinctvaluesbydefault.Toallowduplicatevalues,useUNIONALL.
SQLUNIONALLSyntax
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2

Listing:11.12

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg52 of84
SqLiteReferenceCopyright20052015

Section14
DateandTime
FunctionFormat
SQLitesupportssixdateandtimefunctionsasfollows:
1. now()

same as datetime(now,localtime)

2. date(timestring, modifier, modifier, ...)


3. time(timestring, modifier, modifier, ...)
4. datetime(timestring, modifier, modifier, ...)
5. julianday(timestring, modifier, modifier, ...)
6. strftime(format, timestring, modifier, modifier, ...)

Listing:12.1
Allfivedateandtimefunctionstakeatimestringasanargument.Thetimestringisfollowedbyzeroormoremodifiers.
Thestrftime()functionalsotakesaformatstringasitsfirstargument.
ThedateandtimefunctionsuseasubsetofIS08601dateandtimeformats.Thedate()functionreturnsthedateinthis
format:YYYYMMDD.Thetime()functionreturnsthetimeasHH:MM:SS.Thedatetime()functionreturnsYYYYMMDD
HH:MM:SS.Thejulianday()functionreturnstheJuliandaythenumberofdayssincenooninGreenwichonNovember
24,4714B.C.(ProlepticGregoriancalendar).Thestrftime()routinereturnsthedateformattedaccordingtotheformat
stringspecifiedasthefirstargument.Theformatstringsupportsthemostcommonsubstitutionsfoundinthestrftime()
functionfromthestandardClibraryplustwonewsubstitutions,%fand%J.Thefollowingisacompletelistofvalid
strftime()substitutions:
%d

day of month: 00

%f

fractional seconds: SS.SSS

%H

hour: 00-24

%j

day of year: 001-366

%J

Julian day number

%m

month: 01-12

%M

minute: 00-59

%s

seconds since 1970-01-01

%S

seconds: 00-59

%w

day of week 0-6 with Sunday==0

%W

week of year: 00-53

%Y

year: 0000-9999

%%

Listing:12.2
Noticethatallotherdateandtimefunctionscanbeexpressedintermsofstrftime():
FunctionEquivalentstrftime()
date(...)

strftime('%Y-%m-%d', ...)

time(...)

strftime('%H:%M:%S', ...)

datetime(...)

strftime('%Y-%m-%d %H:%M:%S', ...)

julianday(...)

strftime('%J', ...)

Listing:12.3
Theonlyreasonsforprovidingfunctionsotherthanstrftime()isforconvenienceandforefficiency.
TimeStringsAtimestringcanbeinanyofthefollowingformats:
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg53 of84
SqLiteReferenceCopyright20052015

1.

YYYY-MM-DD

2.

YYYY-MM-DD HH:MM

3.

YYYY-MM-DD HH:MM:SS

4.

YYYY-MM-DD HH:MM:SS.SSS

5.

YYYY-MM-DDTHH:MM

6.

YYYY-MM-DDTHH:MM:SS

7.

YYYY-MM-DDTHH:MM:SS.SSS

8.

HH:MM

9.

HH:MM:SS

10. HH:MM:SS.SSS
11. now
12. DDDDDDDDDD

Listing:12.4
Informats5through7,theTisaliteralcharacterseparatingthedateandthetime,asrequiredbyISO8601.Formats8
through10thatspecifyonlyatimeassumeadateof20000101.Format11,thestring'now',isconvertedintothe
currentdateandtimeasobtainedfromthexCurrentTimemethodofthesqlite3_vfsobjectinuse.UniversalCoordinated
Time(UTC)isused.Format12istheJuliandaynumberexpressedasafloatingpointvalue.

Modifiers
Thetimestringcanbefollowedbyzeroormoremodifiersthatalterthedateandtimestring.Eachmodifierisa
transformationthatisappliedtothetimevaluetoitsleft.Modifiersareappliedfromlefttoright;orderisimportant.
Theavailablemodifiersareasfollows.
1. NNN days
2. NNN hours
3. NNN minutes
4. NNN.NNNN seconds
5. NNN months
6. NNN years
7. start of month
8. start of year
9. start of day
10.weekday N
11.unixepoch
12.localtime
13.utc

Listing:12.5
Thefirstsixmodifiers(1through6)simplyaddthespecifiedamountoftimetothedateandtimespecifiedbythe
precedingtimestringandmodifiers.Notethat+/NNNmonthsworksbyrenderingtheoriginaldateintotheYYYYMM
DDformat,addingthe+/NNNtotheMMmonthvalue,thennormalizingtheresult.Thus,forexample,thedata200103
31modifiedby'+1month'initiallyyields20010431,butAprilonlyhas30dayssothedateisnormalizedto20010501.A
similareffectoccurswhentheoriginaldateisFebruary29ofaleapyearandthemodifieris+/NyearswhereNisnota
multipleoffour.
Thestartofmodifiers(7through9)shiftthedatebackwardstothebeginningofthecurrentmonth,yearorday.
TheweekdaymodifieradvancesthedateforwardtothenextdatewheretheweekdaynumberisN.Sundayis0,
Mondayis1,andsoforth.
Theunixepochmodifier(11)onlyworksifitimmediatelyfollowsatimestringintheDDDDDDDDDDformat.This
modifiercausestheDDDDDDDDDDtobeinterpretednotasaJuliandaynumberasitnormallywouldbe,butasUnixTime
thenumberofsecondssince1970.IftheunixepochmodifierdoesnotfollowatimestringoftheformDDDDDDDDDD
whichexpressesthenumberofsecondssince1970orifothermodifiersseparatetheunixepochmodifierfromprior
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg54 of84
SqLiteReferenceCopyright20052015

DDDDDDDDDDthenthebehaviorisundefined.Duetoprecisionlimitationsimposedbytheimplementationsuseof64bit
integers,theunixepochmodifieronlyworksfordatesbetween0000010100:00:00and5352110110:52:47(unix
timesof62167219200through10675199167).
Thelocaltimemodifier(12)assumesthetimestringtoitsleftisinUniversalCoordinatedTime(UTC)andadjuststhe
timestringsothatitdisplayslocaltime.IflocaltimefollowsatimethatisnotUTC,thenthebehaviorisundefined.The
utcistheoppositeoflocaltime.utcassumesthatthestringtoitsleftisinthelocaltimezoneandadjuststhatstring
tobeinUTC.Ifthepriorstringisnotinlocaltime,thentheresultofutcisundefined.

Timestamp
Itisagoodpracticetokeeptractofthelasttimeafilewasedited.Wedothisbysavingatimestamp.Thefielddefinition
isgivenbelow.
editdate

TIMEDATE DEFAULT (datetime('now','localtime')),

Examples
Compute the current date.
SELECT date('now');
2009-11-05
Compute the current date & time.
SELECT datetime('now');
2009-11-05 20:01:07
Compute the last day of the current month.
SELECT date('now','start of month','+1 month','-1 day');
26
Compute the date and time given a unix timestamp 1092941466.
SELECT datetime(1092941466, 'unixepoch');
2009-11-05 20:01:07
Compute date and time given a unix timestamp 1092941466, and compensate for your local timezone.
SELECT datetime(1092941466, 'unixepoch', 'localtime');
2009-11-05 20:01:07
Compute the current unix timestamp.
SELECT strftime('%s','now');
1092941466
Subtract one timestamp from the other, use this only for dates after 1970!
SELECT trip_id, start_time, end_time,STRFTIME('%s',end_time)-STRFTIME('%s',start_time) FROM t1; #
2:56:22
Compute number of days since signing the US Declaration of Independence.
SELECT julianday('now') - julianday('1776-07-04');
76543
Compute the number of seconds since a particular moment in 2004:
SELECT strftime('%s','now') - strftime('%s','2004-01-01 02:34:56');
476977647
Compute the date of the first Tuesday in October for the current year.
SELECT date('now','start of year','9 months','weekday 2');
2009-10-05

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg55 of84
SqLiteReferenceCopyright20052015

Compute time since unix epoch in seconds (like strftime('%s','now') except includes fractional
part):
SELECT (julianday('now') - 2440587.5)*86400.0;
Compute date in different format
SELECT "Current day " || strftime('%d');
Current day 05
Compute days till Christmas. The %j modifier gives the day of the year for the time string.
SELECT 'Days to XMas:' || (strftime('%j', '2009-12-24') - strftime('%j', 'now'));
Days to XMas:49
Save the current date & time to a database
$query = "INSERT INTO 't1' ('name', 'mydate') VALUES ('John',datetime('now') )";
or
$query = "INSERT INTO 't1' ('name', 'mydate') VALUES ('John',date("Y-m-d H-i-s") )";
2009-11-05 20:01:07

Listing:12.6

SAVECURRENTORFUTUREDATE
Savethecurrentdateandcalculatethedate30daysfromnow
$query = "INSERT INTO 't1' ('datenow', 'date30') VALUES (datetime('now'),datetime('now', '30 days')
)";

Listing:12.7

LESSTHANTIMESPAN
Togettherowswherethereislessthan30daysbetweentwodates
where'newdate'and'olddate'aredatefields
$query = "SELECT * FROM 't1' WHERE julianday(newdate) <

julianday(olddate)+30";

Listing:12.8

DATEEQUALTOTIMESPAN
Togettherowswhereadateequalsaspanof30days,
where'somedate'and'otherdate'aredatefields
$query = "SELECT * FROM 't1' WHERE julianday(somedate) =

julianday(otherdate)+30";

Listing:12.9

TimeZone
Ifthetimezoneisnotset,PHPwillreportanerrorifreportallwarningsisenabled.

date_default_timezone_set(date_default_timezone_get()); // default server timezone


or
date_default_timezone_set('Pacific/Honolulu');

// utc-10 hawaiian

date_default_timezone_set('America/Anchorage);
date_default_timezone_set('America/Los_Angeles');
date_default_timezone_set('America/Denver');
date_default_timezone_set('America/Chicago');

//
//
//
//

utc-9
utc-8
utc-7
utc-6

pacific
pacific
mountain
central

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg56 of84
SqLiteReferenceCopyright20052015

date_default_timezone_set('America/New_York);

// utc-5

eastern

Acompletelistoftimezonecodesisavailableathttp://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Thecomputationoflocaltimedependsheavilyonthewhimofpoliticiansandisthusdifficulttogetcorrectforalllocales.
Inthisimplementation,thestandardClibraryfunctionlocaltime_r()isusedtoassistinthecalculationoflocaltime.The
localtime_r()Cfunctionnormallyonlyworksforyearsbetween1970and2037.Fordatesoutsidethisrange,SQLite
attemptstomaptheyearintoanequivalentyearwithinthisrange,dothecalculation,thenmaptheyearback.

ErrorsandBugs
Thecomputationoflocaltimedependsheavilyonthewhimofpoliticiansandisthusdifficulttogetcorrectforalllocales.
Inthisimplementation,thestandardClibraryfunctionlocaltime_r()isusedtoassistinthecalculationoflocaltime.The
localtime_r()Cfunctionnormallyonlyworksforyearsbetween1970and2037.Fordatesoutsidethisrange,SQLite
attemptstomaptheyearintoanequivalentyearwithinthisrange,dothecalculation,thenmaptheyearback.
Thesefunctionsonlyworkfordatesbetween0000010100:00:00and9999123123:59:59(julidandaynumbers
1721059.5through5373484.5).Fordatesoutsidethatrange,theresultsofthesefunctionsareundefined.
NonVistaWindowsplatformsonlysupportonesetofDSTrules.Vistaonlysupportstwo.Therefore,ontheseplatforms,
historicalDSTcalculationswillbeincorrect.Forexample,intheUS,in2007theDSTruleschanged.NonVistaWindows
platformsapplythenew2007DSTrulestoallpreviousyearsaswell.Vistadoessomewhatbettergettingresultscorrect
backto1986,whentheruleswerealsochanged.
AllinternalcomputationsassumetheGregoriancalendarsystem.Itisalsoassumedthateverydayisexactly86400
secondsinduration.

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg57 of84
SqLiteReferenceCopyright20052015

Section15
Strings
ListofStringFunctions
ascii(char)

returnasciicode

char(code)

returncharfromasciicode

coalesce(X,Y,...)

ReturnacopyofthefirstnonNULLargument.IfallargumentsareNULLthenNULLis
returned.Theremustbeatleast2arguments.

concat(arg?,arg...?)

joinargs

concat_ws(sep,arg?,arg?) joinargswithsep
convert(str,from,to)

encodingconverter.fromandtomustbetcl'sencodingname.

elt(n,arg?,arg...?)

MySQL'selt.

glob(X,Y)

Thisfunctionisusedtoimplementthe"X GLOBY"syntaxofSQLite.The
sqlite3_create_function()interfacecanbeusedtooverridethisfunctionandthereby
changetheoperationoftheGLOBoperator.

hex(n)

returnhexvalue.

hex(X)

TheargumentisinterpretedasaBLOB.Theresultisahexadecimalrenderingofthe
contentofthatblob.

ifnull(X,Y)

ReturnacopyofthefirstnonNULLargument.IfbothargumentsareNULLthenNULLis
returned.Thisbehavesthesameascoalesce()above.

initcap(str)

Oracle'sinitcap.

insert(s,pos,len,ns)

instr(str,sstr,?st?n??)

searchsstrinstr.

last_insert_rowid()

ReturntheROWIDofthelastrowinsertfromthisconnectiontothedatabase.Thisisthe
samevaluethatwouldbereturnedfromthesqlite_last_insert_rowid()APIfunction.

left(str,n)

length(str)

SQLiteBuiltin

length(X)

ReturnthestringlengthofX incharacters.IfSQLiteisconfiguredtosupportUTF8,then
thenumberofUTF8charactersisreturned,notthenumberofbytes.

like(X,Y)
like(X,Y,Z)

Thisfunctionisusedtoimplementthe"XLIKEY[ESCAPEZ]"syntaxofSQL.Iftheoptional
ESCAPEclauseispresent,thentheuserfunctionisinvokedwiththreearguments.
Otherwise,itisinvokedwithtwoargumentsonly.Thesqlite_create_function()interface
canbeusedtooverridethisfunctionandtherebychangetheoperationoftheLIKE
operator.Whendoingthis,itmaybeimportanttooverrideboththetwoandthree
argumentversionsofthelike()function.Otherwise,differentcodemaybecalledto
implementtheLIKEoperatordependingonwhetherornotanESCAPEclausewas
specified.

load_extension(X)

LoadSQLiteextensionsoutofthesharedlibraryfilenamedXusingtheentrypointY.The

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg58 of84
SqLiteReferenceCopyright20052015

load_extension(X,Y)

resultisaNULL.IfY isomittedthenthedefaultentrypointofsqlite3_extension_init is
used.Thisfunctionraisesanexceptioniftheextensionfailstoloadorinitializecorrectly.

locate(sstr,str,pos)

returnfirstsstrpositioninstr.startfrompos.

lower(str)

SQLiteBuiltin

lower(X)

ReturnacopyofstringX willallcharactersconvertedtolowercase.TheClibrarytolower()
routineisusedfortheconversion,whichmeansthatthisfunctionmightnotwork
correctlyonUTF8characters.

lpad(str,len?,pad?)

ltrim(X)
ltrim(X,Y)

ReturnastringformedbyremovinganyandallcharactersthatappearinYfromtheleft
sideofX.IftheYargumentisomitted,spacesareremoved.

max(X,Y,...)

Returntheargumentwiththemaximumvalue.Argumentsmaybestringsinadditionto
numbers.Themaximumvalueisdeterminedbytheusualsortorder.Notethatmax()isa
simplefunctionwhenithas2ormoreargumentsbutconvertstoanaggregatefunctionif
givenonlyasingleargument.

mid(str,pos,len)

min(X,Y,...)

Returntheargumentwiththeminimumvalue.Argumentsmaybestringsinadditionto
numbers.Theminimumvalueisdeterminedbytheusualsortorder.Notethatmin()isa
simplefunctionwhenithas2ormoreargumentsbutconvertstoanaggregatefunctionif
givenonlyasingleargument.

nullif(X,Y)

Returnthefirstargumentiftheargumentsaredifferent,otherwisereturnNULL.

position(sstr,IN,str)

returnfirstsstrpositioninstr.

quote(X)

Thisroutinereturnsastringwhichisthevalueofitsargumentsuitableforinclusioninto
anotherSQLstatement.Stringsaresurroundedbysinglequoteswithescapesoninterior
quotesasneeded.BLOBsareencodedashexadecimalliterals.Thecurrentimplementation
ofVACUUMusesthisfunction.Thefunctionisalsousefulwhenwritingtriggersto
implementundo/redofunctionality.

random(*)

Returnapseudorandomintegerbetween9223372036854775808and
+9223372036854775807.

randomblob(N)

ReturnaNbyteblobcontainingpseudorandombytes.N shouldbeapositiveinteger.

repeat(str,n)

replace(X,Y,Z)

ReturnastringformedbysubstitutingstringZ foreveryoccurrenceofstringY instringX.


TheBINARYcollatingsequenceisusedforcomparisons.

reverse(str)

reversestring.

right(str,n)

round(X)
round(X,Y)

RoundoffthenumberX toY digitstotherightofthedecimalpoint.IftheYargumentis


omitted,0isassumed.

rpad(str,n?,pad?)

rtrim(str?,chars?)

trimrightchars(orspace)fromstr.

rtrim(X)

ReturnastringformedbyremovinganyandallcharactersthatappearinYfromtheright

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg59 of84
SqLiteReferenceCopyright20052015

rtrim(X,Y)

sideofX.IftheY argumentisomitted,spacesareremoved.

soundex(X)

Computethesoundex encodingofthestringX.Thestring"?000"isreturnedifthe
argumentisNULL.ThisfunctionisomittedfromSQLitebydefault.Itisonlyavailablethe
DSQLITE_SOUNDEX=1compileroptionisusedwhenSQLiteisbuilt.

space(n)

returnspace.

sqlite_version(*)

ReturntheversionstringfortheSQLitelibrarythatisrunning.Example:"2.8.0"

substr(X,Y,Z)

ReturnasubstringofinputstringX thatbeginswiththeYthcharacterandwhichisZ
characterslong.TheleftmostcharacterofXisnumber1.IfYisnegativethethefirst
characterofthesubstringisfoundbycountingfromtherightratherthantheleft.IfXis
stringthencharactersindicesrefertoactualUTF8characters.IfXisaBLOBthenthe
indicesrefertobytes.

to_char(num,fmt)

SupportonlyB,FM,S,G,D,",",9,0.Onlynumberformat.Ifyouwanttoformatdatetime,use
somesqlitebuiltinfunctionslikestrftimeordatetime.

translate(str,from,to)

PostgreSQL'stranslate.

trim(X)
trim(X,Y)

ReturnastringformedbyremovinganyandallcharactersthatappearinYfrombothends
ofX.IftheYargumentisomitted,spacesareremoved.

typeof(X)

ReturnthetypeoftheexpressionX.Theonlyreturnvaluesare"null","integer","real",
"text",and"blob".SQLite'stypehandlingisexplainedinDatatypesinSQLiteVersion3.

upper(X)

ReturnacopyofinputstringX convertedtoalluppercaseletters.Theimplementationof
thisfunctionusestheClibraryroutinetoupper()whichmeansitmaynotworkcorrectly
onUTF8strings.

zeroblob(N)

ReturnaBLOBconsistingofNbytesof0x00.SQLitemanagesthesezeroblobsvery
efficiently.ZeroblobscanbeusedtoreservespaceforaBLOBthatislaterwrittenusing
incrementalBLOBI/O.

sqlite_escape_string($string)
sqlite_escape_string()willcorrectlyquotethestringspecifiedbyitemforuseinanSQLiteSQLstatement.Thisincludes
doublingupsinglequotecharacters(')andcheckingforbinaryunsafecharactersinthequerystring.However,itdoes
notcatchallHTMLcharactersthatmayconflictwithabrowserdisplay.Noticethedifferencewiththecustomeroutine
below.
Althoughtheencodingmakesitsafetoinsertthedata,itwillrendersimpletextcomparisonsandLIKEclausesinyour
queriesunusableforthecolumnsthatcontainthebinarydata.Inpractice,thisshouldn'tbeaproblem,asyourschema
shouldbesuchthatyoudon'tusesuchthingsonbinarycolumns(infact,itmightbebettertostorebinarydatausing
othermeans,suchasinfiles).
$str = "Hello! I just don't <care>!";
$str = sqlite_escape_string($str);
echo $str;

TextScrubbing
Thefollowingfunctionwillpreventforeigncharactersfrombeingmisinterpretedintext.Itconvertsthemostcommon
punctuationcharactersintohtmlequivalents.
function cleantxt($str) {
$replace = array(

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg60 of84
SqLiteReferenceCopyright20052015

'&'
'"'
"'"
';'
'<'
'>'

=>
=>
=>
=>
=>
=>

'&amp;',
'&quot;',
'&#39;',
'&#59;',
'&lt;',
'&gt;'

);
$str = str_replace(array_keys($replace), array_values($replace), $str);
return $str;
}

Listing:15.1

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg61 of84
SqLiteReferenceCopyright20052015

Section16
Math
ListofMathFunctions
abs(X)
acos(x)
asin(x)
atan(x)
atan2(x)
avg(X)
ceil(x)
cos(x)
cot(x)
count(*)
count(X)
croup_count(X)
croup_count(X,Y)
degrees(x)
exp(x)
floor(x)
greatest(x)
least(x)
log(x)
log10(x)
max(X)
max(X,Y,...)

min(X)
min(X,Y,...)

mod(x)
pi(x)
pow(x)
radians(x)
rand(x)
random(*)
round(X)
round(X,Y)
sign(x)
sin(x)
sqrt(x)
sum(X)
tan(x)
total(X)
trunc(x)
typeof(X)

Return the absolute value of argument X.

Return the average value of all non null X within the group.

The number of times X is non null in the group.


The number of times X is non null in the group.
The number of times X is non null in the group.
The number of times X is non null in the group.

Return the argument with the maximum value. Arguments may be strings in addition to numbers.
The maximum value is determined by the usual sort order. Note that max() is a simple function
when it has 2 or more arguments but converts to an aggregate function if given only a single
argument.
Return the argument with the minimum value. Arguments may be strings in addition to numbers.
The minimum value is determined by the usual sort order. Note that min() is a simple function
when it has 2 or more arguments but converts to an aggregate function if given only a single
argument.

Return a pseudo-random integer between -9223372036854775808 and +9223372036854775807.


Round off the number X to Y digits to the right of the decimal point. If the Y argument is omitted, 0
is assumed.

Return the type of the expression X. The only return values are "null", "integer", "real", "text", and
"blob". SQLite's type handling is explained in Datatypes in SQLite Version 3.

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg62 of84
SqLiteReferenceCopyright20052015

MathExamples
Examples
return the number of rows in the table. (includes NULL values)
SELECT count(*) AS '# of rows' FROM Testing;
# of rows
---------5
return the number of rows in table. (does not include NULL values)
SELECT count(id) AS '# of non NULL values' FROM Testing;
# of non NULL values
-------------------3
Return average of values. (does not include NULL values)
SELECT avg(cost) AS 'Average price' FROM Cars;
Average price
---------------88528.1666666667
Return the sum() of values. (does not include NULL values)
SELECT sum(OrderPrice) AS Sum FROM Orders;
Sum
---------4930
// add columns from two databases or tables, note: as is required
$result = $db->query('SELECT

SUM(Total) -- SUM pulls total values

FROM (
SELECT SUM(smith) as Total FROM main.sales

-- as is required so sum can pull values

UNION
SELECT SUM(smith) as Total FROM lastyear.sales
)');
Return maximum value of a column value
SELECT max(cost) FROM t1;
max(cost)
-----------3500
Return minimum value of a column value
SELECT min(cost) FROM t1;
min(cost)
-----------750
Return random number
SELECT random() AS Random;
Random
------------------1056892254869386643

Money
Sqlitedoesnotsupportanyspecialcurrencyformat.Youcanuseinteger(123.00)or8bytefloatingpointnumber
(123.45)with15significantdigits.
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg63 of84
SqLiteReferenceCopyright20052015

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg64 of84
SqLiteReferenceCopyright20052015

Section17
ImagesSavingandDisplaying
GDcommandreference http://php.net/manual/en/book.image.php
Theexampleshownheresavesanimageinafiletoadatabasethenretrievesanddisplaysit.Thedatabaseonlyhasone
rowsothatthisexampleisnotclutteredbyforloopsandmultipleentries.

TestImage
WhilethisdocumentwillnotcoverGDgraphicimagesmadewithPHP,itishandytobeabletomakeaquicktestimage
usingthePHPGDimagepackage.Alsonotethatthisprogramusesasimplifiedapproachtodisplayingthepictureinthe
browserusingtheheader("ContentType:image/png").Thisprogramwillonlyallowthepicturetobeshow,soyouwill
notbeabletousePHPsechocommandtoaddothertexttothebrowserview.
TodisplayHTMLtextonthesamepageasthisimage,theimagemustbesavedasafilethentheHTML<img>tagused
toimportit.Anexampleofhowtodothisisshowninalaterexample.
<?php
header("Content-Type: image/png");
$im = @imagecreate(200, 200) or die("Cannot Initialize new GD image stream");
#create colors
$white

= imagecolorallocate($im, 255, 255, 255);

$yellow

= imagecolorallocate($im, 255, 255, 200);

$red

= imagecolorallocate($im, 255,

0,

0);

$black

= imagecolorallocate($im,

0,

0);

0,

# Make the background transparent


imagecolortransparent($im, $white);
# Draw transparent background
imagefilledrectangle($im, 0, 0, 200, 200, $white);
imagesetthickness($im, 2);
imagefilledarc($im, 100, 100, 190, 190,
imagearc($im, 100, 100, 190, 190,

0, 360, $yellow, IMG_ARC_PIE); # head

0, 360, $black);

imagefilledarc($im, 60, 75, 30, 20,


imagefilledarc($im, 140, 75, 30, 20,

0, 360, $black, IMG_ARC_PIE);


0, 360, $black, IMG_ARC_PIE);

# edge
# left eye
# right eye

imagesetthickness($im, 4);
imagearc($im, 100, 125, 125, 50,
imagestring($im, 5, 67, 165,

0, 180, $red);

"Testing!", $black);

# mouth
# text

imagepng($im); show in browser, picture only!


imagepng($im, 'test.png'); # save to file
imagedestroy($im); # recover memory
?>

Listing:13.1

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg65 of84
SqLiteReferenceCopyright20052015

SavinganImage
Tosaveanimage,weneedtohaveaspecialdatatypecalledablob.Ablobisasignaltothedatabaseenginethatit
shouldnottrytofigureoutwhatthedatais;forexampleitisnotastringwithlineends.Becauseadatabasedoesnot
knowwhattypeofinformationisinablob,wehavetokeeptractofwhatitis.Weshouldalwayshaveafieldthatkeeps
themediacontenttype(png,jpg,gif,video,sound,etc).Wewillneedthisimagetypelatersowecandisplayit.
Forthissampleprogramweknowwhattheimageis.Forsimplicitysakewedontshowthestepsneededtoretrievethe
contenttypeinformation.Thecontenttypefieldiscreatedinthisexampleforgoodpractice.Hereisanexampleofhowa
tablemightlookforsomeonesavingphotographs.
# create table
$query = create table sample (
id

integer

primary key,

description text(25),
contenttype text(25),
imagedata

blob

);
$result = $db->query($query) or die(Error in query: <span style=color:red;>$query</span>);

Listing:13.2
Withatableproperlydesigned,wecannowsavethedata.Forourexampleweassumethatthepictureisapngfile
namedtest.png.Wemustuseobjectorientedprogrammingandatransaction(explainedlater)todoourwork.
# insert row of data to table
$stmt = $db->prepare(insert into sample (id, description, contenttype, imagedata)
values (?,?,?,?));
# assign data for each field
$id

= NULL;

$describe

= Sample image file;

$type

= image/png;

# row data

$imagefile = fopen(test.png, rb);


# build the transaction for each field
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $describe);
$stmt->bindParam(3, $type);
$stmt->bindParam(4, $imagefile, PDO::PARAM_LOB);
# perform transaction
$db->beginTransaction(); # create transaction
$stmt->execute();

# do it

$db->commit();

# finished

Listing:13.3
Thatsit!Thedatawithimagehasbeensaved.

DisplayanImage
Togettheimagefromthedatabaseanddisplayit,wemustreversetheaboveprocess.Wegrabtherowdatausinga
normalquery,thensavetheimagedataasafilethatcanberetrievedusingtheHTML<img>tag.
# retrive row of data
$query

= SELECT * FROM sample;

$result = $db->query($query);
$row

# get a row of data

= $result->fetch(PDO::FETCH_ASSOC); # assign to array value

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg66 of84
SqLiteReferenceCopyright20052015

# save image data to file


$image

= $row[imagedata];

file_put_contents(temp.png, $image);

Listing:13.4
Oncetheimageisinafilethatwecanaccess,weusenormalhtmlcodetodisplaytheimagefile.
# show data
echo <img src=temp.png> <br/>;
echo Fig-1 <i>. $row[description] .</i><br/>;

Listing:13.5
Hereisacompleteworkingprogramthatassumesafilenamedtest.pngisinthecurrentdirectory.
<?php
# setup
/* $dbpath

= $_SERVER['DOCUMENT_ROOT'] . "/some path/"; */

$dbpath = "";
$dbfile

= "sqlite_image.sqlite3";

$testimage = "test.png";
date_default_timezone_set('America/Boise');
$today = date("Y/m/d H:i:s"); # date w/leading zeros, dec 1 = 2010.12.01 00:00:00
# title
echo '<body style="font-family:arial;">';
echo "<h2>Blob Image</h2>";
echo "$today<br><br>";
# check for image file
if (!file_exists($testimage)) {
echo "<i>image file &quot;$testimage&quot; does not exist.</i><br>";
echo "<span style='color:red;'><i>I am quiting!</i></span><br>";
exit;
} else {
echo "<i>image file found &quot;$testimage&quot;...</i><br>";
}
# delete existing db
if (file_exists("$dbpath$dbfile")) {
unlink("$dbpath$dbfile");
echo "<i>existing db &quot;$dbpath$dbfile&quot; removed.</i><br>";
}
# new sqlite3 db and connection
$query = "$dbpath$dbfile";
try { $db = new PDO("sqlite:$query");
echo "<i>new db created &quot;$dbfile&quot;...</i><br>";
echo "<i>connecting...</i><br>"; }
catch(PDOException $e) { echo $e->getMessage()." Error: <span style='color:red;'>$query</span>";
}
# enhanced errors
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
# create table
$query = "create table 'sample' (
id

integer

primary key,

description text(25),

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg67 of84
SqLiteReferenceCopyright20052015

contenttype text(25),
imagedata

blob

)";
$result = $db->query("$query") or die("Error in query: <span style='color:red;'>$query</span>");
echo "<i>new table and data initialized...</i><br>";
# setup transaction to insert row of data to table,
$stmt = $db->prepare("insert into sample (id, description, contenttype, imagedata) values
(?,?,?,?)");
$id

= NULL;

$describe

= "Sample image file";

$type

= "image/png";

$imagefile = fopen($testimage, 'rb');


# perform transaction
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $describe);
$stmt->bindParam(3, $type);
$stmt->bindParam(4, $imagefile, PDO::PARAM_LOB);
$db->beginTransaction(); # create transaction
$stmt->execute();

# do it

$db->commit();

# finished

echo "<i>data saved...</i><br>";


# retrive row of data
$query

= "SELECT * FROM 'sample'";

$result = $db->query($query);

# get row of data

$row

= $result->fetch(PDO::FETCH_ASSOC); # assign to array of values

$image

= $row['imagedata'];

echo "<i>data retrieved...</i><br><br>";


# save image data to file
file_put_contents("temp.png", $image);
# show data
echo "<img src='temp.png'> <br/>";
echo "Fig-1 <i>". $row['description'] ."</i><br/>";
#

close db, PHP will also do this automatically


$db = NULL;

?>

Listing:13.6completeimageprogram

EndofSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg68 of84
SqLiteReferenceCopyright20052015

Section18
Crypt,Hash,etc
FunctionSyntax
RequiresTcllibandTrf
md5(data?,binary?)

MD5

md5_hmac(key,data?,binary?)

HMACMD5

md5_crypt(pass,salt?,binary?)

BSDcompatibleMD5crypt

apr_crypt(pass,salt?,binary?)

ApachecompatibleMD5crypt

sha1(data?,binary?)

SHA1

sha1_hmac(key,data?,binary?)

HMACSHA1

aes_encrypt(key,data?,binary?)

ASEencryption

aes_decrypt(key,data?,binary?)

ASEdecryption

blowfish_encrypt(key,data?,binary?)

Blowfishencryption

blowfish_decrypt(key,data?,binary?)

Blowfishdecryption

des_encrypt(key,data?,binary?)

DESencryption

des_decrypt(key,data?,binary?)

DESdecryption

base64_encode(data?,binary?)

Base64encode

base64_decode(data?,binary?)

Base64decode

compress(data?,binary?)

compressdatabyzip

decompress(data?,binary?)

decompressdatabyzip

uuid()

Listing:14.1

FileIO
write_file(path,data?,binary?)
read_file(path?,binary?)

Base64decode
Base64encode

Listing:14.2

EndofSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg69 of84
SqLiteReferenceCopyright20052015

Section19
PrintingTableData
FormattedHTMLTable
<?php
# show table data in formatted html table
$result = $db->query("select * from $dbtable where 1 ");
$rows
= $result->fetchall(PDO::FETCH_ASSOC);
$html="";

// table data
// table data to array

foreach ($rows as $row) {


$rowtext = implode("||",$row)."<br>";
// add || between array values
$result = preg_replace("/\|\|/", "</td><td>", $rowtext); // replace || with <td>...
$html = $html."<tr><td>".$result."</td></tr>\n";
// concatenate each row
}
echo "<table style='border-collapse:collapse;'
cellpadding=3 border=1>\n$html</table>";
?>

Tableprint
Thefollowingcodecreatestheformattedtableoutputshownbelow.Noticethattheprogrammermusthardcodethe
numberofrowsintheloop.Hardcodingtheloopsimplifiesthereadabilityofthecode.
// output table data to a simple html table...
echo "<table cellpadding=5 border=1>";
echo "<tr>";
# bold table header
echo "
<th>ID</th>";
echo "
<th>NAME</th>";
echo "
<th>DOB</th>";
echo "</tr>";
$result = $db->query("SELECT * FROM 't1' ");
foreach($result as $row)
{
echo "<tr>"; // table data
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['dob']."</td>";
echo "</tr>";
}
echo "</table>";

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg70 of84
SqLiteReferenceCopyright20052015

Simpleprint_r

Thefollowingcodecreatesthetextoutputshownhere.Thisisthesimplestandmostoftenusedmethodtoprintdata
information.
// show data
$query = "SELECT * FROM t1";
$result = $db->query("$query") or die("Error in query:
$rows = $result->fetchall();

<span style='color:red;'>$query</span>");

// print_r output
echo "<br><span style='color:red;'><h1>Print_r Output</h1></span>";
echo "<pre>"; print_r($rows); echo "</pre>";

Loopprint_r
Thefollowingcodecreatesthetextoutputshownhere.Whiletheoutputlooksidenticaltotheprevioussimpleroutine,
thismodifiedversionhastheadvantageofgivingaccesstoeachrowofinformationwithinthe'for'loop.
/ show data
$query = "SELECT * FROM t1";
$result = $db->query("$query") or die("Error in query:
$rows = $result->fetchall();

<span style='color:red;'>$query</span>");

// get each row as an array and print values


// print_r output
echo "<br><span style='color:red;'><h1>Print_r Output</h1></span>";
foreach($rows as $array) {

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg71 of84
SqLiteReferenceCopyright20052015

echo "<pre>";
print_r($array);
echo "</pre>";
}

Vardump
Thenextcodesnippetcreatesthetextoutputshownhere.Noticethatfetchall(PDO::FETCH_ASSOC)wasused.This
suppressesthenumberedarrayindexdefinitionwhichcausesaclutteredappearance.
# show data
$query = "SELECT * FROM t1";
$result = $db->query("$query") or die("Error in query:
$rows = $result->fetchall(PDO::FETCH_ASSOC);

<span style='color:red;'>$query</span>");

# get each row as an array and print values


# print_r output
echo "<br><span style='color:red;'><h1>Var Dump Output</h1></span>";
echo "<pre>";
var_dump($result);
var_dump($rows);
echo "</pre>";

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg72 of84
SqLiteReferenceCopyright20052015

Index&associativetableoutput
Thenextcodesnippetcreatesthetextoutputshownhere.Thiscreatesboththeindexandassocitiveheadercolumnsfor
thedata.Ofinterestisplaceingtheuseoffetchall(PDO::FETCH_ASSOC)fetchall(PDO::FETCH_NUM)willreformatthe
tabletoshowthesimplerinformationproperly

show data
$query = "SELECT * FROM t1";
$result = $db->query("$query") or die("Error in query: <span style='color:red;'>$query</span>");
$rows = $result->fetchall(); # usually use fetchall(PDO::FETCH_ASSOC)

Table Output, get each row as an array and print values


echo "<br><span style='color:red;'><h1>Pretty Table Output</h1></span>";
echo "<table border=1 width=\"100%\">\n"; # open the table
print "<tr>\n";
foreach ($rows[0] as $key => $useless){
print "<th>$key</th>";
}

# add the table headers

print "</tr>";
foreach ($rows as $row){
# display data
print "<tr>";
foreach ($row as $key => $val){
print "<td>$val</td>";
}
print "</tr>\n";
}
print "</table><br>";
# close the table

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg73 of84
SqLiteReferenceCopyright20052015

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg74 of84
SqLiteReferenceCopyright20052015

AppendixA
TestDatabases
Testdatabaseprogram
Thefollowingcodecreatestestdatabases.

<?php
/* Initalize "test.sqlite3" database */
echo '<body style="font-family:arial;">';
echo '<h2>Initalize "test.sqlite3" database</h2>';
#

setup
$dbFile

= "test.sqlite3";

$today

= date("Y.m.d"); # date w/leading zeros, dec 1 = 2010.12.01

if db already exists delete it


unlink("$dbFile");

create SQLite3 database


$query = "$dbFile";
try { $db = new PDO("sqlite:$query"); }
catch(PDOException $e) { echo $e->getMessage()." Error: <span style='color:red;'>$query</span>";

}
#

set the PDO error mode to EXCEPTION, gives lots of information


$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

create t1 table

$query = "CREATE TABLE 't1' (


'id' INTEGER PRIMARY KEY,
'name' TEXT(10),
'dob' DATE
)";
$result = $db->query("$query") or die("Error in query:
style='color:red;'>$query</span>");

<span

echo "<i>Created 't1' table...<br></i> ";


#

create t2 table

$query = "CREATE TABLE 't2' (


'id' INTEGER PRIMARY KEY,
'name' TEXT(10),
'phone' TEXT(15)
)";
$result = $db->query("$query") or die("Error in query:
style='color:red;'>$query</span>");

<span

echo "<i>Created 't2' table ...<br></i> ";


#

fill t1 data

$query = "INSERT INTO 't1' ('id','name','dob')


SELECT '1' ,'Frank' ,'$today'
UNION SELECT '2' ,'John'

,'1972.09.22'

UNION SELECT '3' ,''

,'62.03.15'

UNION SELECT '6' ,'John'

,''

UNION SELECT '10','Henry' ,'1973.12.01'


";

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg75 of84
SqLiteReferenceCopyright20052015

$result = $db->query("$query") or die("Error in query:


style='color:red;'>$query</span>");

<span

echo "<i>Created 't1' data... </i> ";


#

show number of rows affected by last operation


$rows_affected = $result->rowCount();
echo "<span style='color:red;'>$rows_affected</span> records affected <br>";

fill t2 data

$query = "INSERT INTO 't2' ('id','name','phone')


SELECT '12' ,'Frank' ,'(100)-123-4567'
UNION SELECT '32' ,'John'

,'200-234-5678'

UNION SELECT '28' ,''

,'890-1234'

UNION SELECT '66' ,'John'

,''

UNION SELECT '61' ,'Henry' ,'ph. 321.2112'


";
$result = $db->query("$query") or die("Error in query:
style='color:red;'>$query</span>");

<span

echo "<i>Created 't2' data... </i> ";


#

Return rows affected by last operation

$rows_affected = $result->rowCount();
echo "<span style='color:red;'>$rows_affected</span> records affected ";
/* +----------------------------------------+
|

Test Code Goes Here

+----------------------------------------+
#

*/

show data

$query = "SELECT * FROM t1";


$result = $db->query("$query") or die("Error in query:
style='color:red;'>$query</span>");

<span

$rows = $result->fetchAll();
echo "<pre>";
print_r($rows);
echo "</pre>";
echo "Access array row information, 2nd row DOB info...<br>";
echo "Row ID = ".$rows['1']['id']." DOB = ".$rows['1']['dob']."<br><br>"; # array [0,1,...]
#

close db, PHP will also do this

automatically

$db = NULL;
?>

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg76 of84
SqLiteReferenceCopyright20052015

AppendixB
CommandReference
PDOCommands

Introduction
Installing/Configuring
Requirements
Installation
Runtime Configuration
Resource Types
Predefined Constants
Connections and Connection management
Transactions and auto-commit
Prepared statements and stored procedures
Errors and error handling
Large Objects (LOBs)
PDO The PDO class
PDO::beginTransaction Initiates a transaction
PDO::commit Commits a transaction
PDO::construct Creates a PDO instance representing a connection to a database
PDO::errorCode Fetch the SQLSTATE associated with the last operation on the
database handle
PDO::errorInfo Fetch extended error information associated with the last
operation on the database handle
PDO::exec Execute an SQL statement and return the number of affected rows
PDO::getAttribute Retrieve a database connection attribute
PDO::getAvailableDrivers Return an array of available PDO drivers
PDO::lastInsertId Returns the ID of the last inserted row or sequence value
PDO::prepare Prepares a statement for execution and returns a statement object
PDO::query Executes an SQL statement, returning a result set as a
PDOStatement object
PDO::quote Quotes a string for use in a query.
PDO::rollBack Rolls back a transaction
PDO::setAttribute Set an attribute
PDOStatement The PDOStatement class
PDOStatement->bindColumn Bind a column to a PHP variable
PDOStatement->bindParam Binds a parameter to the specified variable name
PDOStatement->bindValue Binds a value to a parameter
PDOStatement->closeCursor Closes the cursor, enabling the statement to be
executed again.
PDOStatement->columnCount Returns the number of columns in the result set
PDOStatement->debugDumpParams Dump an SQL prepared command
PDOStatement->errorCode Fetch the SQLSTATE associated with the last
operation on the statement handle
PDOStatement->errorInfo Fetch extended error information associated with the
last operation on the statement handle
PDOStatement->execute Executes a prepared statement
PDOStatement->fetch Fetches the next row from a result set
PDOStatement->fetchAll Returns an array containing all of the result set rows
PDOStatement->fetchColumn Returns a single column from the next row of a
result set
PDOStatement->fetchObject Fetches the next row and returns it as an object.
PDOStatement->getAttribute Retrieve a statement attribute

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg77 of84
SqLiteReferenceCopyright20052015

PDOStatement->getColumnMeta Returns metadata for a column in a result set


PDOStatement->nextRowset Advances to the next rowset in a multi-rowset
statement handle
PDOStatement->rowCount Returns the number of rows affected by the last SQL
statement
PDOStatement->setAttribute Set a statement attribute
PDOStatement->setFetchMode Set the default fetch mode for this statement
PDOException The PDOException class
PDO Drivers
MS SQL Server (PDO) Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Firebird/Interbase (PDO) Firebird/Interbase Functions (PDO_FIREBIRD)
IBM (PDO) IBM Functions (PDO_IBM)
Informix (PDO) Informix Functions (PDO_INFORMIX)
MySQL (PDO) MySQL Functions (PDO_MYSQL)
Oracle (PDO) Oracle Functions (PDO_OCI)
ODBC and DB2 (PDO) ODBC and DB2 Functions (PDO_ODBC)
PostgreSQL (PDO) PostgreSQL Functions (PDO_PGSQL)
SQLite (PDO) SQLite Functions (PDO_SQLITE)
4D (PDO) 4D Functions (PDO_4D)

SQLite3Commands

Introduction
Installing/Configuring
Requirements
Installation
Runtime Configuration
Resource Types
Predefined Constants
SQLite3 The SQLite3 class
SQLite3::changes Returns the number of database rows that were changed (or
inserted or deleted) by the most recent SQL statement
SQLite3::close Closes the database connection
SQLite3::__construct Instantiates an SQLite3 object and opens an SQLite 3
database
SQLite3::createAggregate Registers a PHP function for use as an SQL aggregate
function
SQLite3::createFunction Registers a PHP function for use as an SQL scalar
function
SQLite3::escapeString Returns a string that has been properly escaped
SQLite3::exec Executes a result-less query against a given database
SQLite3::lastErrorCode Returns the numeric result code of the most recent failed
SQLite request
SQLite3::lastErrorMsg Returns English text describing the most recent failed
SQLite request
SQLite3::lastInsertRowID Returns the row ID of the most recent INSERT into the
database
SQLite3::loadExtension Attempts to load an SQLite extension library
SQLite3::open Opens an SQLite database
SQLite3::prepare Prepares an SQL statement for execution
SQLite3::query Executes an SQL query
SQLite3::querySingle Executes a query and returns a single result
SQLite3::version Returns the SQLite3 library version as a string constant and as
a number
SQLite3Stmt The SQLite3Stmt class
SQLite3Stmt::bindParam Binds a parameter to a statement variable

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg78 of84
SqLiteReferenceCopyright20052015

SQLite3Stmt::bindValue Binds the value of a parameter to a statement variable


SQLite3Stmt::clear Clears all current bound parameters
SQLite3Stmt::close Closes the prepared statement
SQLite3Stmt::execute Executes a prepared statement and returns a result set
object
SQLite3Stmt::paramCount Returns the number of parameters within the
prepared statement
SQLite3Stmt::reset Resets the prepared statement
SQLite3Result The SQLite3Result class
SQLite3Result::columnName Returns the name of the nth column
SQLite3Result::columnType Returns the type of the nth column
SQLite3Result::fetchArray Fetches a result row as an associative or numerically
indexed array or both
SQLite3Result::finalize Closes the result set
SQLite3Result::numColumns Returns the number of columns in the result set
SQLite3Result::reset Resets the result set back to the first row

EndOfSection

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg79 of84
SqLiteReferenceCopyright20052015

AppendixC
ReservedWords(337)
A

LANGUAGE,LARGE,LAST,LATERAL,LEADING,LEAVE,LEFT,LEVEL,
LIKE,LOCAL,LOCALTIME,LOCALTIMESTAMP,LOCATOR,LOOP,
LOWER

ABSOLUTE,ACTION,ADD,AFTER,ALL,ALLOCATE,ALTER,AND,
ANY,ARE,ARRAY,AS,ASC,ASENSITIVE,ASSERTION,ASYMMETRIC,
M
AT,ATOMIC,AUTHORIZATION,AVG
B
BEFORE,BEGIN,BETWEEN,BIGINT,BINARY,BIT,BIT_LENGTH,
BLOB,BOOLEAN,BOTH,BREADTH,BY
C
CALL,CALLED,CASCADE,CASCADED,CASE,CAST,CATALOG,CHAR,
CHARACTER,CHARACTER_LENGTH,CHAR_LENGTH,CHECK,CLOB,
CLOSE,COALESCE,COLLATE,COLLATION,COLUMN,COMMIT,
CONDITION,CONNECT,CONNECTION,CONSTRAINT,
CONSTRAINTS,CONSTRUCTOR,CONTAINS,CONTINUE,CONVERT,
CORRESPONDING,COUNT,CREATE,CROSS,CUBE,CURRENT,
CURRENT_DATE,CURRENT_DEFAULT_TRANSFORM_GROUP,
CURRENT_PATH,CURRENT_ROLE,CURRENT_TIME,
CURRENT_TIMESTAMP,
CURRENT_TRANSFORM_GROUP_FOR_TYPE,CURRENT_USER,
CURSOR,CYCLE
D
DATA,DATE,DAY,DEALLOCATE,DEC,DECIMAL,DECLARE,
DEFAULT,DEFERRABLE,DEFERRED,DELETE,DEPTH,DEREF,DESC,
DESCRIBE,DESCRIPTOR,DETERMINISTIC,DIAGNOSTICS,
DISCONNECT,DISTINCT,DO,DOMAIN,DOUBLE,DROP,DYNAMIC
E
EACH,ELEMENT,ELSE,ELSEIF,END,EQUALS,ESCAPE,EXCEPT,
EXCEPTION,EXEC,EXECUTE,EXISTS,EXIT,EXTERNAL,EXTRACT
F
FALSE,FETCH,FILTER,FIRST,FLOAT,FOR,FOREIGN,FOUND,FREE,
FROM,FULL,FUNCTION
G

MAP,MATCH,MAX,MEMBER,MERGE,METHOD,MIN,MINUTE,
MODIFIES,MODULE,MONTH,MULTISET
N
NAMES,NATIONAL,NATURAL,NCHAR,NCLOB,NEW,NEXT,NO,
NONE,NOT,NULL,NULLIF,NUMERIC
O
OBJECT,OCTET_LENGTH,OF,OLD,ON,ONLY,OPEN,OPTION,OR,
ORDER,ORDINALITY,OUT,OUTER,OUTPUT,OVER,OVERLAPS
P
PAD,PARAMETER,PARTIAL,PARTITION,PATH,POSITION,
PRECISION,PREPARE,PRESERVE,PRIMARY,PRIOR,PRIVILEGES,
PROCEDURE,PUBLIC
R
RANGE,READ,READS,REAL,RECURSIVE,REF,REFERENCES,
REFERENCING,RELATIVE,RELEASE,REPEAT,RESIGNAL,RESTRICT,
RESULT,RETURN,RETURNS,REVOKE,RIGHT,ROLE,ROLLBACK,
ROLLUP,ROUTINE,ROW,ROWS
S
SAVEPOINT,SCHEMA,SCOPE,SCROLL,SEARCH,SECOND,
SECTION,SELECT,SENSITIVE,SESSION,SESSION_USER,SET,SETS,
SIGNAL,SIMILAR,SIZE,SMALLINT,SOME,SPACE,SPECIFIC,
SPECIFICTYPE,SQL,SQLCODE,SQLERROR,SQLEXCEPTION,
SQLSTATE,SQLWARNING,START,STATE,STATIC,SUBMULTISET,
SUBSTRING,SUM,SYMMETRIC,SYSTEM,SYSTEM_USER
T

TABLE,TABLESAMPLE,TEMPORARY,THEN,TIME,TIMESTAMP,
TIMEZONE_HOUR,TIMEZONE_MINUTE,TO,TRAILING,
TRANSACTION,TRANSLATE,TRANSLATION,TREAT,TRIGGER,
TRIM,TRUE

HANDLER,HAVING,HOLD,HOUR

UNDER,UNDO,UNION,UNIQUE,UNKNOWN,UNNEST,UNTIL,
UPDATE,UPPER,USAGE,USER,USING

GENERAL,GET,GLOBAL,GO,GOTO,GRANT,GROUP,GROUPING

IDENTITY,IF,IMMEDIATE,IN,INDICATOR,INITIALLY,INNER,
INOUT,INPUT,INSENSITIVE,INSERT,INT,INTEGER,INTERSECT,
INTERVAL,INTO,IS,ISOLATION,ITERATE
J
JOIN

V
VALUE,VALUES,VARCHAR,VARYING,VIEW
W

WHEN,WHENEVER,WHERE,WHILE,WINDOW,WITH,WITHIN,
WITHOUT,WORK,WRITE

KEY

YEAR
Z
ZONE

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg80 of84
SqLiteReferenceCopyright20052015

Notes
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________

Notes
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg82 of84
SqLiteReferenceCopyright20052015

Notes
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg83 of84
SqLiteReferenceCopyright20052015

Documenation
http://www.php.net/
http://www.sqlite.org/
http://phpbuilder.com/manual/en/ref.sqlite.php
http://www.w3schools.com/sql/
http://www.firstsql.com/

References

GettingtheRightDatawithSQLJoins.http://www.devx.com/dbzone/Article/17403/0/page/1
SQLJoin.http://www.w3schools.com/sql/sql_join.asp
SQLitehomepage,http://www.sqlite.org/
SQLFeaturesThatSQLiteDoesNotImplement,http://www.sqlite.org/omitted.html
AcommandlineprogramtoadministerSQLitedatabases,http://www.sqlite.org/sqlite.html
SQLAsUnderstoodBySQLite,http://www.sqlite.org/lang.html
FrequentlyAskedQuestions,http://www.sqlite.org/faq.html
SQLiteReferencebyMikeChiricomchirico@users.sourceforge.net,
http://souptonuts.sourceforge.net/readme_sqlite_reference.html

ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg84 of84
SqLiteReferenceCopyright20052015

You might also like