Professional Documents
Culture Documents
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:
PDO SQLite2:
sqlite
test. Sqlite2
sqlite3
test. sqlite3
PDO 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.
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.
http://code.google.com/p/sqlite-manager/
SQLIite Administrator
http://sqliteadmin.orbmu2k.de/
SQLite Browser
SqliteRoot
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)
<span style='color:red;'>$query</span>");
?>
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg9 of84
SqLiteReferenceCopyright20052015
<!--
<!--
-->
-->
</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
Unassigned
REAL
DOUBLE
DOUBLE PRECISION
FLOAT
REAL
CHARACTER(20)
VARCHAR(255)
VARYING CHARACTER(255)
NCHAR(55)
NATIVE CHARACTER(70)
NVARCHAR(100)
TEXT
CLOB
TEXT
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
/*
*/
setup
$dbPath
= $_SERVER['DOCUMENT_ROOT'] . "/contacts/";
$dbFile
= "people.sqlite3";
}
#
Listing:2.1Genericconnectionanderrorhandling.
Fromthispointon,wewillalwaysassumetheprogrammerknowsthatthenecessarycodetoconnecttothedatabase
(similartowhatisshownhere)needstobeinsertedforthedbconnection.
CreateandInsertIntoDatabase
Oncetheerrordefinitionismade,wedontneedtousethetry{},catch{},ordiecodeanymore.ThePDOerror
reportingdoesawonderfuljobonfatalerrors,butcanbealittlecrypticforwarnings.Ihavefoundacombinationofthe
twotechniquesworksbest.Anexampleoftypicalerrorsupportthatincludessqlitespecificinformationisprovidedhere.
$result = $db->query("$query")
Listing:2.2Typicalerrorsupport.
<?php
/*
*/
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>";
?>
Listing:2.3createandinsertdata
ViewandSearchData
Hereisourcompletedcodetoviewalltabledata.
<?php
/*
*/
connect to database
# ... code to setup, connect to database, and handle errors goes here
#
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 success
echo "<i>Search successful.</i><br>";
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
#
show success
echo "<i>Update data was successful.</i><br>";
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg15 of84
SqLiteReferenceCopyright20052015
automatically
$db = NULL;
?>
Listing:2.5finalversionofupdatingarecord
DeleteData
IfweuseWHEREnameLIKE'James%'thenanynamestartingwithJameswillbeselected.InsteadwewilluseWHERE
nameLIKE'%Bond%'thenonlyanamewiththislastnamewouldbedeleted.
Sohereiswhatweneed
<?php
/* Listing 2.6 - delete James Bond
*/
connect to database
# ... code to setup, connect to database, and handle errors goes here
#
show success
echo "<i>Data deleted successful.</i><br>";
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
*/
setup
$dbPath
= $_SERVER['DOCUMENT_ROOT'] . "/path/to/db/";
$dbFile
= "db_name.sqlite3";
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
*/
setup
$dbPath
$dbFile
$dbNew
= $_SERVER['DOCUMENT_ROOT'] . "/contacts/";
= "people.sqlite3";
= "test.sqlite3";
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
*/
setup
$dbPath
$dbFile
= $_SERVER['DOCUMENT_ROOT'] . "/contacts/";
= "test.sqlite3";
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
*/
= $_SERVER['DOCUMENT_ROOT'] . "/contacts/";
$dbFile
$dbNew
#
= "people.sqlite3";
= "test.sqlite3";
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
<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>";
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>';
//
//
//
= $result->fetchall(PDO::FETCH_ASSOC);
= $result->fetchall(PDO::FETCH_ASSOC);
FROM (
SELECT SUM(smith) as Total FROM main.sales
UNION
SELECT SUM(smith) as Total FROM lastyear.sales
)');
$rows
= $result->fetchall(PDO::FETCH_ASSOC);
Result
Database 1
Array (
[0] => Array
([smith] => 50.0)
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg21 of84
SqLiteReferenceCopyright20052015
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
editdate
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> ";
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
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();
#
<span
$rows = $result->fetchall(PDO::FETCH_ASSOC);
#
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
*/
setup
$dbPath
= $_SERVER['DOCUMENT_ROOT'] . "/contacts/";
$dbFile
= "sample.sqlite3";
$oldtable = "test";
$newtable = "newtbl";
... code to connect to database, and handle errors
#
replace old table name with new table name in the structure statement
$search
= $structure;
Listing:4.5ReplaceoldtablenamewithnewtablenameinstructurefromMASTERTABLE
Nowwecancreatethenewtablewiththesamestructure
...
#
replace old table name with new table name in the structure statement
$search
= $structure;
Listing:4.6Createnewtable
<?php
/* Listing 9.4 Copy table structure */
echo '<body style="font-family:arial;">';
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg25 of84
SqLiteReferenceCopyright20052015
setup
$dbPath
= $_SERVER['DOCUMENT_ROOT'] . "/contacts/";
$dbFile
= "sample.sqlite3";
$oldtable = "test";
$newtable = "newtbl";
... code to connect to database, and handle errors
#
replace old table name with new table name in the structure statement
$search
= $structure;
show success
echo "<i>Table added successfully.</i><br> ";
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";
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%') ";
show success
echo "<i>Row deleted successfully.</i><br> ";
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
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
Listing:7.12
Ifnosortorderisspecified,itwillbeASCENDINGwhichisalphabeticaland/orsmalltolargenumbers.Toreversethe
defaultsortorderwemustuseDESC.Wecanusemorethanonecolumnidthereisamatch.Forexamplesupposewe
aresortingstudentnamesinaschoolandthereismorethanoneSmith.Wecanusethedateofbirthtoo
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:
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
FINDINGDUPLICATES
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg39 of84
SqLiteReferenceCopyright20052015
WiththeSQLstatementbelowyoucanfindduplicatevaluesinanytable,justchangethetablefieldintothecolumnyou
wanttosearchandchangethetableintothenameofthetableyouneedtosearch.
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 ->
Error
->
Correct ->
Error
->
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
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.
-- ********************************************************************
--
--
Run as follows:
--
-- ********************************************************************
CREATE TRIGGER update_editdate AFTER INSERT ON t1
BEGIN
UPDATE t1 SET editdate = DATETIME('NOW')
END;
-- ********************************************************************
Listing:9.1
Anotherwayofkeepingatimestamp(perhapseasierthanatrigger)istousethedefaultvalueofthetablescheme.The
fielddefinitionisgivenbelow.
editdate
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.
--
(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;
---
--
NOTE
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg45 of84
SqLiteReferenceCopyright20052015
(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;
--
(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)
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
%H
hour: 00-24
%j
%J
%m
month: 01-12
%M
minute: 00-59
%s
%S
seconds: 00-59
%w
%W
%Y
year: 0000-9999
%%
Listing:12.2
Noticethatallotherdateandtimefunctionscanbeexpressedintermsofstrftime():
FunctionEquivalentstrftime()
date(...)
strftime('%Y-%m-%d', ...)
time(...)
strftime('%H:%M:%S', ...)
datetime(...)
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
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.
// 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)
reverse(str)
reversestring.
right(str,n)
round(X)
round(X,Y)
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
'&'
'"'
"'"
';'
'<'
'>'
=>
=>
=>
=>
=>
=>
'&',
'"',
''',
';',
'<',
'>'
);
$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 average value of all non null X within 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 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
FROM (
SELECT SUM(smith) as Total FROM main.sales
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
$yellow
$red
= imagecolorallocate($im, 255,
0,
0);
$black
= imagecolorallocate($im,
0,
0);
0,
0, 360, $black);
# 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
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
$type
= image/png;
# row data
# do it
$db->commit();
# finished
Listing:13.3
Thatsit!Thedatawithimagehasbeensaved.
DisplayanImage
Togettheimagefromthedatabaseanddisplayit,wemustreversetheaboveprocess.Wegrabtherowdatausinga
normalquery,thensavetheimagedataasafilethatcanberetrievedusingtheHTML<img>tag.
# retrive row of data
$query
$result = $db->query($query);
$row
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg66 of84
SqLiteReferenceCopyright20052015
= $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
$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 "$testimage" does not exist.</i><br>";
echo "<span style='color:red;'><i>I am quiting!</i></span><br>";
exit;
} else {
echo "<i>image file found "$testimage"...</i><br>";
}
# delete existing db
if (file_exists("$dbpath$dbfile")) {
unlink("$dbpath$dbfile");
echo "<i>existing db "$dbpath$dbfile" removed.</i><br>";
}
# new sqlite3 db and connection
$query = "$dbpath$dbfile";
try { $db = new PDO("sqlite:$query");
echo "<i>new db created "$dbfile"...</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
$type
= "image/png";
# do it
$db->commit();
# finished
$result = $db->query($query);
$row
$image
= $row['imagedata'];
?>
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
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>");
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>");
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)
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
}
#
create t1 table
<span
create t2 table
<span
fill t1 data
,'1972.09.22'
,'62.03.15'
,''
ZoomAviation.combyJanZumwaltRevisedAugust25,2015
Pg75 of84
SqLiteReferenceCopyright20052015
<span
fill t2 data
,'200-234-5678'
,'890-1234'
,''
<span
$rows_affected = $result->rowCount();
echo "<span style='color:red;'>$rows_affected</span> records affected ";
/* +----------------------------------------+
|
+----------------------------------------+
#
*/
show data
<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,...]
#
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
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
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