eBook SQlite, PHP Dan PDO

Embed Size (px)

Citation preview

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    1/80

    SQLiteUsing

    PHP & PDO

    Reference

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    2/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' of *!

    by Jan Zumwalt - NeatInfo.com

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    3/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' + of *!

    Table of Contents

    Section - 1 Introduction ........................................................................................................................................... bout his Reference ......................................................................................................................................................................................... /hat is )0 ........................................................................................................................................................................................................ "2$ite 3" "2$ite+ ............................................................................................................................................................................................. /hat database does )0 su&&ort4 .................................................................................................................................................................. "ettin' u& a develo&ment system ..................................................................................................................................................................... 6M)) confi' files .............................................................................................................................................................................................. *0atabase mana'ers ............................................................................................................................................................................................ *0o I have )0 on my com&uter4 ...................................................................................................................................................................... 78ood )ro'rammin' "ynta9 .............................................................................................................................................................................. 1!

    Single Row Data .......................................................................................................................................................................................... 10Multiple Row Data ...................................................................................................................................................................................... 10

    "ection - "im&le 0atabase :9am&le ................................................................................................................................ 1

    %onnect and error handlin' ............................................................................................................................................................................. 1%reate and Insert Into 0atabase ..................................................................................................................................................................... 13iew and "earch 0ata ...................................................................................................................................................................................... 1+;&date 0ata ...................................................................................................................................................................................................... 1 ...................................................................................................................

    dd able .......................................................................................................................................................................................................... 0oes able :9ist ................................................................................................................................................................................................ %o&y able /ith 0ata ...................................................................................................................................................................................... +%o&y able "tructure ........................................................................................................................................................................................ ..................................................................................................................... *

    Insert Row =add> ............................................................................................................................................................................................... *Insert - Multi&le Rows ...................................................................................................................................................................................... *%o&y Row .......................................................................................................................................................................................................... *0elete ll Rows ................................................................................................................................................................................................. *0elete Row=s> Matchin' %ondition ................................................................................................................................................................. *%ount Rows ....................................................................................................................................................................................................... 7Inde9 0escri&tion .............................................................................................................................................................................................. +!

    "ection - %olumn =dd-%o&y-0elete-Rename>................................................................................................................ +1

    dd %olumn ...................................................................................................................................................................................................... +1%o&y %olumn and data ..................................................................................................................................................................................... +10elete %olumn .................................................................................................................................................................................................. +1Rename %olumn ............................................................................................................................................................................................... +1

    %ount %olumns ................................................................................................................................................................................................. +

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    4/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' < of *!

    "ection - "how and "earch 0ata ..................................................................................................................................... ++

    "im&le "elect "ynta9......................................................................................................................................................................................... ++he four fetch ty&es ......................................................................................................................................................................................... ++

    WHERE ......................................................................................................................................................................................................... 3

    L!"E ............................................................................................................................................................................................................... 3#$D .............................................................................................................................................................................................................. 3%&R ................................................................................................................................................................................................................. 3%

    dvanced "elect "ynta9 ................................................................................................................................................................................... +5L!M!' ............................................................................................................................................................................................................ 3%&RDER () ..................................................................................................................................................................................................... 3*+R&,- () .................................................................................................................................................................................................... 3*H#!$+ ........................................................................................................................................................................................................ 3*

    "ection - * 3iews ................................................................................................................................................................ +*

    "ection - 7 ri''ers ............................................................................................................................................................ +7

    Insert Row imestam& ..................................................................................................................................................................................... +7$o''in' ll Inserts, ;&dates, and 0eletes ...................................................................................................................................................... +7

    "ection - 1! ransactions ...................................................................................................................................................

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    5/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 5 of *!

    1 !f 4ou copied code from a page of ti reference ............................................................................................................................... *5 Some S6Lite /erion a/e incompati7ilitie ...................................................................................................................................... *3 !n/alid reource error ........................................................................................................................................................................ *% Seniti/it4 to wite pace ..................................................................................................................................................................... *%% 9una7le to open file: ............................................................................................................................................................................. *%

    * 9S6L!'E;C&RR,-' error: ..................................................................................................................................................................... *% i.e. 9#rra4: ................................................................................................................................................. *%? S)$'#@ ERR&R> ,ne=pected 9End:A .................................................................................................................................................. **10 9une=pected ';#R!#(LE: ................................................................................................................................................................. **

    &&endi9 - A )rintin' able 0ata .......................................................................................................................................

    able &rint ......................................................................................................................................................................................................... "im&le &rintCr ................................................................................................................................................................................................... $oo& &rintCr ...................................................................................................................................................................................................... *3ar dum&........................................................................................................................................................................................................... 7Inde9 E associative table out&ut ..................................................................................................................................................................... !

    &&endi9 - % est 0atabases .............................................................................................................................................. 1

    est database &ro'ram .................................................................................................................................................................................... 1

    &&endi9 B 0 %ommand Reference ................................................................................................................................... +

    )0 %ommands ................................................................................................................................................................................................ +"2$ite+ %ommands ..........................................................................................................................................................................................

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    6/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' of *!

    Section - 1

    Introduction

    About This Referencehis reference was written durin' the desi'n of a &roFect that did not need the hu'e overhead of a My"#l database. /hen

    I researched "2$ite, I found the e9istin' e9am&les very confusin'. It was hard to tell the difference between code

    desi'ned for %, the command line interface, "2$ite, or "2$ite+.

    I decided to use PDObecause I already had e9&erienced in proceduraldatabase &ro'rammin' and wanted to widen out

    with object orienteddatabase &ro'rammin'.

    his reference has s&ecific e9am&les tested in the XAMPPdevelo&ment environment but should be able to be used on

    Fust about any HTTP serverwith out modification.

    SQite!is used for the database,HTMand"avaScriptare used for the user browser interface,PHPis used for server fileaccess and )@) PDOallows )@) to communicate with the database. /hewG hat was a mouthful, but it all worHs easily

    and very well to'ether.

    he methodolo'y Fust mentioned is by far the most common in use on the internet today. hanHfully, only basic com&uter

    sHills and terminolo'y will be needed. :9am&les are s&ecifically desi'ned for ease of understandin'. ?lashy cosmetic web

    desi'n has been left out for clarity.

    Ae sure to review the most common errors in the &&endi9 before &roceedin'.

    #hat is PDO

    PDO $P@)DataObFects%is a )@) e9tension that su&&orts database connections with a unifor& co&&and structure. hisallows develo&ers to create code which is &ortable across many databases and system o&eratin' &latforms. "im&ly

    e9&lained, )0 lets you use the same code =obFect oriented> or commands for a &roFect that could be used on a cell

    &hone, &&le com&uter, /indows, or an IAM mainframe. hat maHes &ro'rammin' a lot easierG

    SQite' (S SQite!

    Now the (#DnewsG

    he volunteers that maintain SQitewanted a small li'htwei'ht feature rich database that would com&are to My"#l.

    "2$ite taHes less than 1mb of disH stora'e s&ace com&ared to *!-1!!mb for My"#l. o Hee& "2$ite lean and meanthe

    develo&ers chose to forfeit co&plicated &ultitas)in* and &ultiusercriteria that loaded down My"#l. his is not a

    &roblem, it is a feature. t some &oint, some of the ori'inal ways of doin' thin's in earlier versions of "2$ite became sucha &roblem that they decided to create an entirely new command and database structure between version E +.

    he lar'est chan'es started with "2$ite+ and thats a (!+&roblem. he chan'es in "2$ite+ cause much of the source code

    of earlier versions to be inco&patibilit+ ,ith ne,er versions of SQ-te neither the database or command structures

    worH smoothly across these versions.

    he solution chosen by "2$ite volunteers was to start SQite! as a .ne,/ D0 lan*ua*e hence we ended u& with )0. s

    a conse#uence of these differences, we must use caution in choosin' the commands and database structure. he 'ood

    news is the commands are easily reco'niKed SQite! co&&ands use .12. object s+nta3.

    /hat is not always easy to reco'niKe is the database structure =ty&e>. Many "2$Ite databases have no e9tension or

    'eneric e9tensions that do not offer any clue as to what set of commands should be used on them, so becareful!

    "2$ite =liHe most other 0A lan'ua'es> offers a set of command line o&tions. he co&&and lineand PDOcommands are

    not interchan*eableso watch outG

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    7/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' of *!

    @ere is a com&arison of commands to o&en or create a database.Default SQLite2: $db = new SQLiteDatabase('test.sqlite2', 0666, $error);

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

    Command line SQLite2: sqlite test. Sqlite2

    Command line SQLite3: sqlite3 test. sqlite3

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

    Liting 1.1 B erion command comparion.

    #hat database does PDO support4

    )0 su&&orts many of the &o&ular databases. @ere is a &artial list...

    0A$IAL ?ree0" Microsoft "2$ "erver "ybase

    ?irebird =htt&Lfirebird.sourcefor'e.net>L ?irebirdInterbase

    IAM =IAM 0A>

    IN?RMI6 - IAM Informi9 0ynamic "erver

    M"2$ =htt&Lwww.mys#l.com>L My"2$ +.9L racle %all Interface

    0A%L 0A% v+ =IAM 0A and uni90A%>

    )8"2$ =htt&Lwww.&ost'res#l.or'>L )ost're"2$

    "2$I: =htt&Ls#lite.or'>L "2$ite +.9

    Settin* up a develop&ent s+ste&

    ou will need a develo&ment environment. I stron'ly recommend usin' XAMPPfor either #indo,sor inu3. )rior to

    about !!, /M) had more features and less installation &roblems than 6M)), but that is no lon'er true. I have used

    bothXAMPPand #AMPfor many years and find that 6M)) has less installation &roblems. few years a'o 6M)) had

    some control &anel issues which seem to have all been fi9ed. ?or downloads and further readin', see the linHs below.

    http://www.apachefriends.org/en/xampp.html

    http://www.wampserver.com/en/

    Most =but not all> inu3develo&ment systems come with )@) su&&ort for "2$ite. n windows machines, 6M)) installs

    )@) su&&ort for"2$ite but not necessarily SQLite3.

    If you have trouble with SQite!, the first thin' you should checH is the PHP confi* file. 0ont for'et to checH all the

    &ossible locations 'iven below. lso, you should stopthe Apacheserver before editin' any file that affects &ache, and

    then restartafter you are done.

    Windows: xampp/php/php.ini.

    Some Linux xampp/apache/bin/php.ini

    he #indo,s confi* fileshould have a cou&le areas with lines that looH liHe the followin'O

    extension=php_pdo_sqlite.dll

    extension=php_pdo_sqlite_external.dll

    extension=php_sqlite.dll

    extension=php_sqlite3.dll

    sqlite.assoc_case = 0

    hese lines should not have the 5=semi-colon> at the start of the line. he semicolon comments out the code and &revents

    it from worHin'. If it has the semi-colon 5it should be edited out. $inu9 may have sli'htly different values and file names

    that end ,ith 6soon the end.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    8/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' * of *!

    XAMPP confi* files

    Just to maHe this section com&lete, a list of confi'uration files for 6M)) are &rovide below. s we already mentioned,

    there may be sli'ht differences in location or names de&endin' on whether it is a /indows or $inu9 installation. Many$inu9 develo&ers sli'htly modify the directory structure.

    * Apache basic configuration: .\xampp\apache\conf\httpd.conf

    * Apache SSL: .\xampp\apache\conf\ssl.conf

    * Apache Perl (addon): .\xampp\apache\conf\perl.conf

    * Apache Tomcat (addon): .\xampp\apache\conf\java.conf

    * Apache Python (addon): .\xampp\apache\conf\python.conf

    * PHP: .\xampp\php\php.ini

    .\xampp\apache\bin\php.ini

    * MySQL: .\xampp\mysql\bin\my.cnf

    * phpMyAdmin: .\xampp\phpMyAdmin\config.inc.php

    * FileZilla FTP: .\xampp\FileZillaFTP\FileZilla Server.xml

    * Mercury Mail: .\xampp\MercuryMail \MERCURY.INI

    * Sendmail: .\xampp\sendmail\sendmail.ini

    $inu9 may have sli'htly different values such as names with P.soQ on the end.

    Database &ana*ers

    %ustom &ro'rammin' is &robably only about 1!-! of a database &ro'rammers worH. he other *! is done usin' a

    convenient database manager&ro'ram. "everal 'ood ones are listed below.

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

    Firefox SQLITE plugin module http://code.google.com/p/sqlite-manager/

    SQLIite Administrator http://sqliteadmin.orbmu2k.de/

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

    SqliteRoot http://sqliteroot.com/

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

    t the time of this writin', https788sourcefor*e6nethad over 5!! hi'h #uality free S9ite utilities. he 8oo'le code

    develo&er site http788code6*oo*le6co&is another 'ood &lace to looH. hey are all worth checHin' out. n internet search

    will certainly turn u& more treasure. ?or e9am&le, there are several utilities that maHe mana'in' a database over the

    internet much easier.

    PhpiteAd&inis very small )@) "#lite mana'er that is easy to use. It does not re#uire installation or confi'uration. It is a

    small sin'le file that is &laced in the directory where your database is and run from there.- reco&&end this for the

    be*inner and it is what I use most of the time. It su&&orts both "#$ite and "#$ite+ =several other mana'ers dont>. It is

    very intuitive. It has a sim&le to& menu. No searchin' is re#uired to find the command or tool you need. Its only

    disadvanta'e at the time of this writin' is that it only looHs in the current directory for databases. No directory browsin'feature is available. his handica& will liHely 'o away in the near future. he readme doc that comes with it e9&lains a

    sim&le way to manually insert a directory &ath in the source code.

    I use SQite'::; Pro =freeware version> some of the time. SQite'::; Pro has all the features you could &ossibly want

    includin' built-in documentation. It taHes some 'ettin' use to - es&ecially fi'urin' out your data hierarchy and where your

    table information is located. /indows allows you to create a "2$ite file e9tension so that a mouse selection o&ens the

    mana'er immediately.

    he SQite Ad&inistratoris one of the easiest mana'ers to use and I would &refer it e9ce&t that it is missin' a cou&le Hey

    features. It is not easy to add or edit a record. I would not be sur&rised if a year or more of develo&ment fi9es most of its

    issues. he installation creates an "2$ite file e9tension hooH that o&ens the mana'er immediately if the mouse clicHs on a

    database file.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    9/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 7 of *!

    he

    Liting 1.5 #ll te -H- info 4ou could poi7l4 want

    Liting 1.3 B Sow a lit of -D& upported data7ae on 4our computer.

    PDO & PHP Info

    If you see "sqlite2" listed, there is support for sqlite2.

    If you see "sqlite" listed, there is support for sqlite3.

    PHP version:

    SQLite library version:

    SQLite library character encoding:

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    10/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 1! of *!

    $db=newPDO("sqlite:$query")or die("Could not create: $query");

    ?>

    Liting 1. B Fanc4 report wit an option for a compreeni/e -H- liting.

    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.1SQLite library version: 2.8.17

    SQLite library character encoding: iso8859

    If you dont see an error message, a SQLite3test database was created.

    &,'-,' from liting 1. B iew generated on a Win @- @#M-- 4tem. G'e pp info i not own and i a7out 3 page

    long.

    ?ood Pro*ra&&in* S+nta3

    fre#uently used standard is to assi'n a variable named Drow for sin'le row data retrieval and Drows =notice the SsS> for

    multi&le row data. Multi&le rows of data are sometimes called a data set or result set.

    S-@?> RO# DATA

    sin'le row of data is retrieved by usin' the fetch$%statement. Ae careful not to confuse it with the fetchall$%statement.

    he followin' is a 'eneral e9am&le.

    $query="SELECT * FROM t1";

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

    $row=$result->fetch();

    Liting 1.% B +etting a ingle row of information a an arra4.

    :ven thou'h there may be more than one match, only the first match one will be returned in Drow.

    /e can access this sin'le row of data by usin' the associative field name.

    echo$row['name'];

    Liting 1.* B Sowing a column from row data.

    his would return T?ranHT because that has the lowest I0 number and would be the first match.

    MT-P> RO# DATA

    Multi&le rows of data can be retrieved at one time by usin' the fetchall$%statement. Ae careful not to confuse it with the

    fetch=> statement. he result is returned as an array of arrays. he followin' is a 'eneral e9am&le.

    $query="SELECT * FROM t1";

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

    $rows=$result->fetchall();

    Liting 1.< B +etting multiple row of information a an arra4 of arra4.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    11/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 11 of *!

    /e can access any row usin' array matri9 addressin'.

    echo$rows['3'],['name'];

    Liting 1.8 B Sowing an4 column of an arra4 of arra4.

    his would access the third row of information and return the PnameQ data.

    :nd f "ection

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    12/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 1 of *!

    Section = '

    Si&ple Database >3a&ple

    his section &rovides a sim&le e9am&le of the most command database )0 command usa'e. he e9am&le &rovides thesHeletal frameworH on which many com&any em&loyee databases or &hone contact list is based. It is a very valuable

    reference on its own. he ste&s to creatin' a sima&le database are covered hereO

    0esi'n

    %reate db ?ile

    %reate table and column definitions

    Insert data

    3iew and search data

    ;&date data

    0elete data

    Connect and error handlin*In all our e9am&les, we assume that we have successfully created andor connected to the database and set u& our error

    handlin'. 'ood 'eneric tem&late is 'iven below

    /* Listing 3.6 - create "people db */

    echo'';

    echo'Create "people" database';

    # setup

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

    $dbFile ="people.sqlite3";

    # connect to SQLite3 database

    $query="$dbPath$dbFile";

    try { $db= new PDO("sqlite:$query"); }

    catch(PDOException $e) { echo$e->getMessage()." Error: $query"; }

    # enhanced error messages

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

    Liting 5.1 B +eneric connection and error andling.

    Create and -nsert -nto Database

    nce the error definition is made, we dont need to use the PtryU VQ, PcatchU VQ, or PdieQ code anymore. he )0 error

    re&ortin' does a wonderful Fob on fatal errors, but can be a little cry&tic for warnin's. I have found a combination of the

    two techni#ues worHs best.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    13/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 1+ of *!

    phone TEXT(25)

    )";

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

    echo"Database successfully initialized.
    ";

    # 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: $query");

    # 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: $query");

    # show success

    echo"Data successfully inserted.
    ";

    # show number of rows affected by last operation

    $rows_affected=$result->rowCount();

    echo"$rows_affected records affected ";

    # close db, PHP will also do this automatically

    $db=NULL;

    ?>

    Liting 5.5 B create and inert data

    (ie, and Search Data

    @ere is our com&leted code to view all table data.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    14/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 1< of *!

    $rows_affected=$result->rowCount();

    echo"$rows_affected records affected

    ";

    echo"------
    ";

    # query using specific fields and SELECT with WHERE

    $query="SELECT 'phone' FROM 'friends' WHERE name='James%' ";

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

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

    # show table data

    foreach($rowas$array){

    echo"";

    print_r($array);

    echo"";

    }

    echo 'Result for: $query="SELECT phone FROM 'friends' WHERE name=\'James%\' ";. "
    ";

    # show number of rows affected by last operation

    $rows_affected=$result->rowCount();

    echo"$rows_affected records affected

    ";

    # show success

    echo"Search successful.
    ";

    # close db, PHP will also do this automatically

    $db=NULL;

    ?>

    Liting 5.3 B earc tecni2ue

    pdate Data

    If we use #H>R> na&e -B> "a&esthen any name startin' with PJamesQ will be selected.

    "o here is what we need

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    15/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 15 of *!

    Liting 5. B final /erion of updating a record

    Delete Data

    If we use #H>R> na&e -B> "a&esthen any name startin' with"a&eswill be selected. Instead we will use #H>R>

    na&e -B> 0ondthen only a name with this last name would be deleted.

    "o here is what we need

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    16/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 1 of *!

    Section = !

    Database $Add=Cop+=Delete=Rena&e%

    n often over looHed as&ect of database &ro'rammin' is the maintenance that usually continues to be an on'oin' afterthe database is created. %ommands to mani&ulate the whole database file or reveal the definitions of its tables or

    columns are necessary to do this.

    Add Database

    Remember that if "2$ite does not find the database 'iven in the file name, it will attem&t to maHe it. "o al l that is needed

    to create a new db is to have a valid &ath and su&&ly a new file name.

    If you do not want )0 to create a em&ty db if none is found, you can use &h&s fileEe3istscommand to test for the file.

    $datafile = '/path/to/test.sqlite3';

    if (file_exists($datafile)) {

    ... code to

    ... connect to database

    } else {

    echo "Error, did not find dataabse at $datafile.";

    exit;

    }

    Liting 3.1 B 'eting if a data7ae e=it

    @e is a &ro'ram listin' that o&ens a db or creates a new one if none is found.

    Liting 3.5 Creating a new data7ae

    Cop+ Database

    t the time of writin' this reference, I was unable to find a )0 db co&y command. @owever, there are still several

    o&tions available.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    17/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 1 of *!

    1- all the db mana'ers &rovide an Pim&ortQ feature

    - a database could be o&ened and it contents meticulously co&ied

    +- use &h& to maHe a co&y of the file

    I favor method three =+>. @ere is an e9am&leO

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    18/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 1* of *!

    t the time of writin' this reference, I was unable to find a )0 db rename command. @owever, there are still several

    o&tions available.

    1- db mana'ers may &rovide a PrenameQ feature

    - a database could be o&ened and it contents co&ied to a new database, then the old db deleted+- use &h& to rename the database file

    I favor method three =+>. @ere is an e9am&leO

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    19/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 17 of *!

    $query="SELECT * FROM sqlite_master";

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

    $rows=$result->fetchAll();

    echo"";print_r($rows);echo"";# show data

    Liting 3.* B iew mater data7ae decriptor information

    Array

    (

    [type] => table

    [name] => friends

    [tbl_name] => friends

    [rootpage] => 2

    [sql] => CREATE TABLE friends (

    id INTEGER PRIMARY KEY,

    name TEXT(25),

    phone TEXT(25)

    )

    )

    :9am&le out&ut

    o see both the master and tem&Cmaster

    $query="SELECT * FROM sqlite_master

    UNION SELECT * FROM sqlite_temp_master ";

    Liting 3.< B mater and temp;mater data decriptor

    o see Fust table descri&tions use thisO.

    $query="SELECT sql FROM sqlite_master WHERE type='table'";

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

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

    echo"";print_r($rows);echo"";# show data

    Liting 3.8 B #ll ta7le data decriptor information

    o see a s&ecific tables descri&tion use thisO.

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

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

    echo""; echo"";print_r($rows);echo"";# show data

    Liting 3.? B Specific ta7le decriptor information

    Multi&le 0atabases

    The ATTACH DATABASE statement connects one or more database files to the current databaseconnection.

    or the e!am"le belo#$ su""ose #e #ant the current and last %ear&s sales total for one of theem"lo%ees. Each %ears data is arran'ed b% em"lo%ee name. (e #ill use t#o db files arran'ed li)e

    this*

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    20/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' ! of *!

    ?ileL dbF.s#lite+

    ableL sales

    %ol1 X smith ther em&loyeesO5! more data

    5 more data

    more data more data

    ?ileLdb'.s#lite+

    ableL sales

    %ol1 X smith ther em&loyeesO!! more data

    N;$$ more data

    more data

    Result

    Database 1

    Array (

    [0] => Array

    ([smith] => 50.0)

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    21/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 1 of *!

    [1] => Array

    ([smith] => 75.0)

    )

    Database 2

    Array(

    [0] => Array

    ([smith] => 200.0)

    )

    Total

    Array(

    [0] => Array

    ([SUM(Total)] => 325.0)

    )

    :nd f "ection

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    22/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' of *!

    Section = G

    Table $Add=Cop+=Delete=Rena&e%

    Add Table

    /e already learned how to add a table to a db. "o that our reference is com&lete, we &rovide the code a'ain. 0ont for'et

    that the db PconnectQ &rocess will create a new db if it does not already e9ist. herefore, addin' a table to a non e9istent

    db will usually result in the db and table bein' created even if it does not e9ist.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    23/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' + of *!

    $db->query("$query") or die(" Error adding table: $query");

    $totaltables= sqlite_num_rows($query);

    # does table exist

    if($totaltables

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    24/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' < of *!

    # show new table

    foreach($rows as $array){

    echo"";

    print_r($array);

    echo"";

    }

    ?>

    Liting . Cop4 ta7le and data to new ta7le

    Cop+ Table Structure

    o 'et the table structure we can use the followin' code.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    25/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 5 of *!

    /* Listing 9.4 Copy table structure */

    echo'';

    echo'Copy table structure';

    # setup

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

    $dbFile ="sample.sqlite3";

    $oldtable="test";

    $newtable="newtbl";

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

    # get table structure

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

    $row=$result->fetch(PDO::FETCH_ASSOC);

    $structure=$row['sql'];

    # replace old table name with new table name in the structure statement$search ="/CREATE TABLE $oldtable/";

    $replace="CREATE TABLE $newtable";

    $string =$structure;

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

    # create new table

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

    # show success

    echo"Table added successfully.
    ";

    # Return rows affected by last operation

    $rows_affected=$result->rowCount();

    echo"$rows_affected records affected ";

    # close db, PHP will also do this automatically

    $db=NULL;

    ?>

    Liting .< B Complete liting for cop4ing ta7le tructure

    Delete Table

    o dro& =delete> a table, we use this commandO

    $query="DROP TABLE 'test' ";

    Liting .8 B Delete ta7le

    Rena&e Table

    he synta9 used to rename a table is

    $query="ALTERTABLE'oldTablename'RENAMETO'newTablename' ";

    Liting .? B Rename ta7le

    his command cannot be used to moea table between two different databases, only to renamea table within the

    same database.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    26/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' of *!

    (ie, Table Structures

    he synta9 used to rename a table is

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    27/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' of *!

    SELECT name FROM sqlite_master

    WHERE type='table'

    ORDER BY name;

    Liting .11 B ta7le decriptione

    ?or indices, ty&e is e#ual to Sinde9S, name is the name of the inde9, and tblCname is the name of the table to which the

    inde9 belon's.

    ?or both tables and indices, the s#l field is the te9t of the ori'inal %R:: A$: or %R:: IN0:6 statement that created

    the table or inde9.

    :nd f "ection

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    28/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' * of *!

    Section = I

    Ro, $Add=Cop+=Delete=Rena&e%

    -nsert Ro, $add%

    s we have done before, we will &ut our #uery statement in a variable so that we can have a better error messa'e.

    I inert data all column are filled

    $query="INSERT INTO 'tablename' VALUES('col1Data','col2Data','col3Data')";

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

    Liting %.1 B inert data B inerting a ingle row Grecord of information.

    Notice that we did not s&ecify anid. Aecause id is aprimary field, "2$ite is smart enou'h to automatically increment a

    uni#ue number for us.

    $istin'-1!.1 is a short form of the IN":R command and e9&ects a value for every column =field>. If we intend to leave

    some columns blanH or are 'oin' to edit or u&date certain columns in a row, we must s&ecify which column names we are

    'oin' to be worHin' with.

    $on' version of IN":R

    I inert data pecif4ing wic field to fill

    $query="INSERT INTO 'tablename' (field_x,field_y) VALUES('col1Data',' col2Data')";

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

    Liting %.5 B inert data B column name pecified.

    -nsert = Multiple Ro,sinsert into mytable (col,col2,col3)

    select 'a1', 'b1', 'c1'

    union

    select 'a2', 'b2', 'c2'

    union

    select 'a3', 'b3', 'c3'

    ...

    Cop+ Ro,

    o co&y a row we first ":$:% the row to co&y then IN":R it as a new row.

    Delete All Ro,s

    o delete all the rows in a table we can use thisO

    $query= "DELETE FROM 'tablename'";

    Liting %.3 B

    Delete Ro,$s% Matchin* Condition

    If we Hnow the record id then we can use thisO

    $query="DELETE FROM tablename WHERE id='xxx' ";

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    29/80

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    30/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' +! of *!

    $query="SELECT COUNT(*) FROM 'tablename'";

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

    $rows=count($result->fetchAll());

    $rowcount = $rows[0][0];

    echo "Total rows = $rowcount
    ";

    $colcount =$result->columnCount();

    echo "Column count = $colcount
    ";

    Liting %.< B Count row and column

    -nde3 Description

    y&e field will always be StableS and the name field will be the SnameS of the table. o 'et a list of all tables in the database,

    use the followin' ":$:% commandL

    SELECT name FROM sqlite_master

    WHERE type='index'ORDER BY name;

    Liting %.8 B

    ?or indices, ty&e is e#ual to Sinde9S, name is the name of the inde9, and tblCname is the name of the table to which the

    inde9 belon's.

    ?or both tables and indices, the s#l field is the te9t of the ori'inal %R:: A$: or %R:: IN0:6 statement that created

    the table or inde9.

    :nd f "ection

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    31/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' +1 of *!

    Section = J

    Colu&n $Add=Cop+=Delete=Rena&e%

    Add Colu&n$query="ALTERTABLE'[database.]tablename'ADD COLUMN'newColumn' TEXT";

    Liting *.1 Creating a new data7ae

    Cop+ Colu&n and data

    S6Lite #L'ER '#(LE onl4 upport 9add column: to te end of a ta7le> or 9cange ta7le name:. !f 4ou want to mae oter

    cange tan te ta7le will a/e to 7e copied in te proper order and renamed.

    result1db=2#uery$T%R:: A$: SDnewtableS " ":$:% Scolo%o&y S ?RM SDoldtableST%5

    Liting *.5 B

    Delete Colu&n

    Su""ose %ou ha+e a table named ,t1, #ith columns names ,a,$ ,b,$ and ,c,. If %ou #ant to deletecolumn ,c, from this table$ than the follo#in' ste"s illustrate ho# this could be done

    CREATETEMPORARYTABLEt1_backup(a,b);

    INSERTINTOt1_backup SELECTa,b FROMt1;

    DROPTABLEt1;

    CREATETABLEt1(a,b);

    INSERTINTOt1 SELECTa,b FROMt1_backup;

    DROPTABLEt1_backup;

    Liting *.3 Creating a new data7ae

    Rena&e Colu&n

    "ay you have a table and need to rename ToldCbT to TnewCbTL

    1) Rename the old table:

    ALTER TABLE orig_table_name RENAME TO tmp_table_name;

    2) Create a newtable,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;

    Liting *. Creating a new data7ae

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    32/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' + of *!

    Count Colu&ns

    We can count columns using PDOs built in columnCount() function. There is no way for PDOto know the rowCount of a S!CT result because the S"!ite #P$ itself %oesn&t offer this

    ability. Therefore rowCont() %oes not work. 'ere is how to get these counts.

    $rowcount=count($result->fetchAll());

    echo "Total rows = $rowcount
    ";

    $colcount =$result->columnCount();

    echo "Column count = $colcount
    ";

    Liting *.% B Count row and column

    :nd f "ection

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    33/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' ++ of *!

    Section = K

    Sho, and Search Data

    Si&ple Select S+nta3Recall from section-5 that we can search our database usin' ":$:% then e9tract the information usin' ?:%@. he sim&le

    form of this command is shown below.

    $query="SELECT FROM 'table' ";

    $result =$db->query($query,PDO::FETCH_ASSOC)

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

    Liting query($query);

    $row=$result->fetch(PDO::FETCH_ASSOC);

    echo"";print_r($row);echo"";

    print("

    ");

    print("PDO::FETCH_BOTH: next row as an array indexed by both column name and number
    ");

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

    $row=$result->fetch(PDO::FETCH_BOTH);

    echo"";print_r($row);echo"";

    print("

    ");

    print("PDO::FETCH_LAZY: next row as an anonymous object with column names as properties
    ");

    $result=$db->query($query,PDO::FETCH_LAZY);

    $row=$result->fetch(PDO::FETCH_LAZY);

    echo"";print_r($row);echo"";

    print("

    ");

    print("PDO::FETCH_OBJ: next row as an anonymous object with column names as properties
    ");

    $result=$db->query($query,PDO::FETCH_OBJ);

    $row=$result->fetch(PDO::FETCH_OBJ);

    echo"";print_r($row);echo"";

    print("

    ");

    Liting

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    34/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' +< of *!

    [id] => 1

    [name] => Frank

    [dob] => 2011.12.09

    )

    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

    )

    #H>R>

    he WHEREclause includes a com&arison &redicate, which restricts the rows returned by the #uery. he WHEREclause

    eliminates all rows from the result set for which the com&arison &redicate does not evaluate to rue. Remember that if

    we use the /@:R: statement by itself, it re#uires an e9act match.

    $query="SELECT *FROM 'table'WHERE name='James Bond'";

    Liting

    he $IW: clause allows use to use wildcards or less s&ecific match criteria

    /e can also use more than one condition.

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

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    35/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' +5 of *!

    Liting

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    36/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' + of *!

    # get previous record

    $rowindex=65;

    $query="SELECT * FROM 'tablename' LIMIT ($rowindex-1), 1";

    Liting maHes the code more readable so I use $IMI =Drowinde91>,1. f

    course we can have more than one row returned by usin' different values for count.

    ORD>R 0L

    he ORDER BYclause identifies which columns are used to sort the resultin' data, and in which direction they should be

    sorted =o&tions are ascendin' or descendin'>. /ithout an ORDER BYclause, the order of rows returned by an "2$ #uery

    usually correlates to the pri&ar+ )e+field such as an I0 number.

    he synta9 isO

    ORDER BY column

    orORDER BY column DIRECTION

    %onsider this e9am&leO

    # sort records by last name in DESCENDING order

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

    # more...code

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

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

    Liting

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    37/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' + of *!

    "2$ s&ecifies that an "2$ SELECTstatement should only return rows where a''re'ate values meet the s&ecified

    conditions. It was addedto the "2$ lan'ua'e because the WHEREHeyword could not be used with a''re'ate functions

    o return a list of de&artment I0s whose total sales e9ceeded D1!!! on the date of January 1, !!!, alon' with the sum of

    their sales on that dateL

    SELECT DeptID, SUM(SaleAmount)

    FROM Sales

    WHERE SaleDate = '01-Jan-2000'

    GROUP BY DeptID

    HAVING SUM(SaleAmount) > 1000

    Liting

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    38/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' +* of *!

    Section =

    (ie,s

    vie,is a s&ecific looH on data in from one or more tables. It can arran'e data in some s&ecific order, hi'li'ht or hidesome data. view consists of a stored #uery accessible as a virtual table com&osed of the result set of a #uery. ;nliHe

    ordinary tables a view does not form &art of the &hysical schema. It is a dynamic, virtual table com&uted or collated from

    data in the database.

    In the ne9t e9am&le, we create a sim&le view.

    sqlite> SELECT * FROM Cars;

    Liting 8.1 B

    Id Name Cost

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

    1 Audi 52642

    2 Mercedes 57127

    3 Skoda 9000

    4 Volvo 29000

    5 Bentley 350000

    6 Citroen 21000

    7 Hummer 41400

    8 Volkswagen 21600

    &utput 8.1 B

    his is our data, u&on which we create the view.

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

    sqlite> SELECT * FROM CheapCars;

    Liting 8.5 B

    Name

    ----------

    Skoda

    Volvo

    Citroen

    Volkswagen

    &utput 8.5 B

    echnically a view is a virtual table. "o we can list all views with a 6tablescommand. o remove a view, we use the DROP

    (->#"2$ statement.

    sqlite> .tables

    Books CheapCars Friends Names Reservations

    Cars Customers Log Orders Testing

    sqlite> DROP VIEW CheapCars;

    sqlite> .tables

    Books Customers Log Orders Testing

    Cars Friends Names Reservations

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    39/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' +7 of *!

    Section = ;

    Tri**ers

    Tri**ersare database o&erations that are automatically &erformed when a s&ecified database event occurs.

    -nsert Ro, Ti&esta&p

    It is a 'ood &ractice to Hee& tract of the last time a file was edited. /e do this by savin' a time stam&. n insert tri''er is

    created below in the file Ttri''er1T. he %oordinated ;niversal ime =;%> will be entered into the field Ttime:nterT, and

    this tri''er will fire aftera row has been inserted into the table t1.

    -- ********************************************************************

    -- Creating a trigger for timeEnter

    -- Run as follows:

    -- $ sqlite3 test.db < trigger1

    -- ********************************************************************

    CREATE TRIGGER update_editdate AFTER INSERT ON t1

    BEGIN

    UPDATE t1 SET editdate = DATETIME('NOW') WHERE rowid = new.rowid;

    END;

    -- ********************************************************************

    Liting ?.1 B

    nother way of Hee&in' a timestam& =&erha&s easier than a tri''er> is to use the default value of the table scheme. he

    field definition is 'iven below.

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

    Liting 1%.5 B

    o**in* All -nsertsN pdatesN and Deletes

    he scri&t below creates the table e9amlo' and three tri''ers =u&dateCe9amlo', insertCe9amlo', and deleteCe9amlo'> to

    record u&dates, inserts, and deletes made to the e9am table. In other words, whenever a chan'e is made to the e9am

    table, the chan'es will be recorded in the e9amlo' table, includin' the old value and the new value. If you are familiar

    with My"2$, the functionality of this lo' table is similar to My"2$Ss binlo'. "ee i&s ,

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    40/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)'

    BEGIN

    INSERT INTO examlog (ekey,fnNEW,lnNEW,examNEW,scoreNEW,

    sqlAction,examtimeEnter,timeEnter)

    values (new.ekey,new.fn,new.ln,new.exam,new.score,

    'INSERT',new.timeEnter,DATETIME('NOW') );

    END;

    -- Also create a DELETE trigger

    CREATE TRIGGER delete_examlog DELETE ON exam

    BEGIN

    INSERT INTO examlog (ekey,fnOLD,lnNEW,examOLD,scoreOLD,

    sqlAction,timeEnter)

    values (old.ekey,old.fn,old.ln,old.exam,old.score,

    'DELETE',DATETIME('NOW') );

    END;

    Liting ?.5 B

    In the followin' e9am&le, we will use the ?riends table and create a new $o' table.

    CREATE TABLE Log(Id integer PRIMARY KEY, OldName text, NewName text, Date text);

    Liting ?.3 B

    /e will create new tables for the ne9t e9am&le with tri''ers.

    CREATE TRIGGER mytrigger UPDATE OF Name ON Friends

    BEGIN

    INSERT INTO Log(OldName, NewName, Date) VALUES(old.Name, new.Name, datetime('now'));

    END;

    Liting ?. B

    /e create a tri''er called mytri''er with the %R:: RI88:R statement. his tri''er will launch a IN":R statement

    whenever we u&date the name column of the ?riends table. he IN":R statement will insert the old name, the new

    name and the time stam& into the $o' table.

    sqlite> SELECT * FROM Friends;

    Id Name Sex

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

    1 Jane F2 Thomas M

    3 Franklin M

    4 Elisabeth F

    5 Mary F

    6 Lucy F

    7 Jack M

    his is our data.

    Ne9t, we are 'oin' to u&date one row of the ?riends table.

    sqlite> UPDATE Friends SET Name='Frank' WHERE Id=3;

    Liting ?.% B

    /e u&date the third row of the table. he tri''er is launched.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    41/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' SELECT * FROM Log;

    Id OldName NewName Date

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

    1 Franklin Frank 2009-11-14 16:36:28

    /e checH the $o' table. his lo' confirms the u&date o&eration we &erformed.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    42/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' AT> TA0>statement into CR>AT> TA0> -< @OT >X-STS, the first three

    statements would e9ecute.

    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;

    Liting 10.5 B

    transaction can end with a COMM-Tor a RO0ACBstatement. he RO0ACBreverts all chan'es.

    :nd f "ection

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    43/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' R "O-@7 0efault Join ty&e. %reate new table where one or more table rows meet criteria.

    @ATRA "O-@7 %ombines all columns in tables with same column-name.

    >R "O-@7 Retain all records in table on the left side =re'ardless of match>, mer'e only matches from ri'ht

    side.

    R-?HT OT>R "O-@7 Retain all records in table on the ri'ht side =re'ardless of match>, mer'e only matches from left

    side.

    $ote Left and rigt Join refer to te two ide of te J&!$ e4word. Left and R!+H' Join are

    identical 74 re/ering ta7le poition.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    44/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' SELECT * FROM Artists, CDs;

    Liting 11.1 B

    In some "2$ dialect it can be also used

    sqlite>SELECT * FROM Artists CROSS JOIN CDs;

    Liting 11.5 B

    $et us try to filter the result with the /@:R: clauseL

    sqlite>SELECT ArtistName, Title FROM Artists, CDs WHERE Artists.ArtistID=CDs.ArtistID;

    Liting 11.3 B

    It 'ives

    Peter Gabriel|SoPeter 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

    o avoid confusion, use this statement instead

    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;

    Liting 11. B

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    45/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' R "O-@

    he same result can be achieved with the INN:R JIN clauseL

    sqlite> SELECT Artists.ArtistName, CDs.Title FROM Artists INNER JOIN CDs ON

    Artists.ArtistID=CDs.ArtistID;

    Liting 11.% B

    he INN:R JIN returns all rows from both tables where there is a match. If there are rows in rtists that do not have

    matches in %0s, those rows will notbe listed.

    >R "O-@

    he $:? ;:R JIN o&erator ensures that all rows on the TleftT side of the Foin, in this case the rtists table, will beincluded.

    sqlite>SELECT * FROM Artists LEFT OUTER JOIN CDs ON Artists.ArtistID = CDs.ArtistID;

    Liting 11.* B

    here is no "u&ernatural in %0s but you can still see "u&ernatural with em&ty fields from rtistsL

    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 | | | |

    "ome "2$ dialects use $:? JIN.

    In other dialects =racle> instead of

    sqlite> SELECT Artists.ArtistName, CDs.Title

    ------> FROM Artists

    ------> LEFT OUTER JOIN CDs

    ------> ON Artists.ArtistID = CDs.ArtistID;

    Liting 11.< B

    the followin' statement is used

    SELECT Artists.ArtistName, CDs.Title

    FROM Artists, CDs

    WHERE Artists.ArtistID = CDs.ArtistID(+)

    Liting 11.8 B

    he => symbol denotes the table =side> that may have no matchin' rows to the other table =side>. hinH of this as

    everythin' from the left &lus matchin' values from the ri'ht.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    46/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' R "O-@ and R "O-@

    "imilarly this "2$

    SELECT Artists.ArtistName, CDs.Title

    FROM Artists

    RIGHT OUTER JOIN CDs

    ON Artists.ArtistID = CDs.ArtistID;

    Liting 11.? B

    r

    SELECT Artists.ArtistName, CDs.Title

    FROM Artists, CDs

    WHERE Artists.ArtistID(+) = CDs.ArtistID

    Liting 11.10 B

    would return all records from the ri'ht side.

    %urrently "2$ite su&&orts neitherof the above synta9. @owever there is easy worHaroundL use $:? ;:R JIN with

    interchan'ed tables. he ?;$$ ;:R JIN clause is not su&&orted as well.

    @-O@

    he ;NIN o&erator is used to combine the result-set of two or more ":$:% statements.

    Notice that each ":$:% statement within the ;NIN must have the same number of columns. he columns must also

    have similar data ty&es. lso, the columns in each ":$:% statement must be in the same order.

    "2$ ;NIN "ynta9

    SELECT column_name(s) FROM table_name1UNION

    SELECT column_name(s) FROM table_name2

    Liting 11.11 B

    @ote7he ;NIN o&erator selects only distinct values by default. o allow du&licate values, use ;NIN $$.

    "2$ ;NIN $$ "ynta9

    SELECT column_name(s) FROM table_name1

    UNION ALL

    SELECT column_name(s) FROM table_name2

    Liting 11.15 B

    :nd f "ection

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    47/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' function also taHes a format strin' as its first ar'ument.

    he date and time functions use a subset of I"!-*!1 date and time formats. he date=> function returns the date in this

    formatL -MM-00. he time=> function returns the time as @@LMML"". he datetime=> function returns P-MM-00

    @@LMML""Q. he Fulianday=> function returns the Julian day - the number of days since noon in 8reenwich on November

    substitutionsL

    %d day of month: 00

    %f fractional seconds: SS.SSS

    %H hour: 00-24

    %j day of year: 001-366

    %J Julian day number

    %m month: 01-12

    %M minute: 00-59

    %s seconds since 1970-01-01

    %S seconds: 00-59

    %w day of week 0-6 with Sunday==0

    %W week of year: 00-53

    %Y year: 0000-9999

    %% %

    Liting 15.5 B

    Notice that all other date and time functions can be e9&ressed in terms of strftime=>L

    ?unction :#uivalent strftime=>

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

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

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

    julianday(...) strftime('%J', ...)

    Liting 15.3 B

    he only reasons for &rovidin' functions other than strftime=> is for convenience and for efficiency.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    48/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' is used. ?ormat 1 is the Julian day number e9&ressed as a floatin' &oint value.

    Modifiers

    he time strin' can be followed by Kero or more modifiers that alter the date and time strin'. :ach modifier is a

    transformation that is a&&lied to the time value to its left. Modifiers are a&&lied from left to ri'ht order is im&ortant.

    he available modifiers are as follows.

    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

    Liting 15.% B

    he first si9 modifiers =1 throu'h > sim&ly add the s&ecified amount of time to the date and time s&ecified by the&recedin' timestrin' and modifiers. Note that Q- NNN monthsQ worHs by renderin' the ori'inal date into the -MM-

    00 format, addin' the - NNN to the MM month value, then normaliKin' the result. hus, for e9am&le, the data !!1-!+-

    +1 modified by S1 monthS initially yields !!1-! shift the date bacHwards to the be'innin' of the current month, year or day.

    he PweeHdayQ modifier advances the date forward to the ne9t date where the weeHday number is N. "unday is !,

    Monday is 1, and so forth.

    he Puni9e&ochQ modifier =11> only worHs if it immediately follows a timestrin' in the 0000000000 format. hismodifier causes the 0000000000 to be inter&reted not as a Julian day number as it normally would be, but as ;ni9 ime

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    49/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' and adFusts the

    time strin' so that it dis&lays localtime. If PlocaltimeQ follows a time that is not ;%, then the behavior is undefined. he

    PutcQ is the o&&osite of PlocaltimeQ. PutcQ assumes that the strin' to its left is in the local timeKone and adFusts that strin'

    to be in ;%. If the &rior strin' is not in localtime, then the result of PutcQ is undefined.

    Ti&esta&p

    It is a 'ood &ractice to Hee& tract of the last time a file was edited. /e do this by savin' a time stam&. he field definition

    is 'iven below.

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

    >3a&ples

    Compute the currentdate.

    SELECT date('now');

    2009-11-05

    Compute the currentdate& time.

    SELECT datetime('now');

    2009-11-05 20:01:07

    Compute the last day of the currentmonth.

    SELECT date('now','start of month','+1 month','-1 day');

    26

    Compute the dateand timegiven a unix timestamp 1092941466.

    SELECT datetime(1092941466,'unixepoch');

    2009-11-05 20:01:07

    Compute dateand timegiven a unix timestamp 1092941466,and compensate foryour local timezone.

    SELECT datetime(1092941466,'unixepoch','localtime');

    2009-11-05 20:01:07

    Compute the currentunix 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) FROMt1; #

    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 dateof the first Tuesday in October forthe currentyear.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    50/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 5! of *!

    SELECT date('now','start of year','9 months','weekday 2');

    2009-10-05

    Compute timesince 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 %jmodifier 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 currentdate & 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

    Liting 15.* B

    SA(> CRR>@T OR DAT>

    "ave the current date and calculate the date +! days from nowO

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

    Liting 15.< B

    >SS THA@ T-M> SPA@

    o 'et the rows where there is less than +! days between two dates

    where SnewdateS and SolddateS are date fieldsO

    $query = "SELECT * FROM 't1' WHERE julianday(newdate) < julianday(olddate)+30";

    Liting 15.8 B

    DAT> >QA TO T-M> SPA@

    o 'et the rows where a date e#uals a s&an of +! days,

    where SsomedateS and SotherdateS are date fieldsO

    $query = "SELECT * FROM 't1' WHERE julianday(somedate) = julianday(otherdate)+30";

    Liting 15.? B

    >rrors and 0u*s

    he com&utation of local time de&ends heavily on the whim of &oliticians and is thus difficult to 'et correct for all locales.

    In this im&lementation, the standard % library function localtimeCr=> is used to assist in the calculation of local time. he

    localtimeCr=> % function normally only worHs for years between 17! and !+. ?or dates outside this ran'e, "2$ite

    attem&ts to ma& the year into an e#uivalent year within this ran'e, do the calculation, then ma& the year bacH.

    hese functions only worH for dates between !!!!-!1-!1 !!L!!L!! and 7777-1-+1 +L57L57 =Fulidan day numbers11!57.5 throu'h 5++

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    51/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 51 of *!

    Non-3ista /indows &latforms only su&&ort one set of 0" rules. 3ista only su&&orts two. herefore, on these &latforms,

    historical 0" calculations will be incorrect. ?or e9am&le, in the ;", in !! the 0" rules chan'ed. Non-3ista /indows

    &latforms a&&ly the new !! 0" rules to all &revious years as well. 3ista does somewhat better 'ettin' results correct

    bacH to 17*, when the rules were also chan'ed.

    ll internal com&utations assume the 8re'orian calendar system. It is also assumed that every day is e9actly *

    seconds in duration.

    :nd f "ection

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    52/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 5 of *!

    Section F!

    Strin*s

    ist of Strin*

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    53/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 5+ of *!

    loadEe3tension$%

    loadEe3tension$N"%

    oad SQite e3tensions out of the shared librar+ file na&ed usin* the entr+ point "6 The

    result is a @6 -f "is o&itted then the default entr+ point of s9lite!Ee3tensionEinit is

    used6 This function raises an e3ception if the e3tension fails to load or initialie correctl+6

    locate$sstrN strN pos% return first sstr position in str6 start fro& pos6

    lo,er$str% SQite 0uilt=in

    lo,er$% Return a cop+ of strin*,ill all characters converted to lo,er case6 The C librar+ tolo,er$%

    routine is used for the conversionN ,hich &eans that this function &i*ht not ,or)

    correctl+ on T

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    54/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 5< of *!

    rtri&$str 4N chars4% tri&ri*ht chars$or space% fro& str6

    rtri&$%

    rtri&$N"%

    Return a strin* for&ed b+ re&ovin* an+ and all characters that appear in "fro& the ri*ht

    side of6 -f the "ar*u&ent is o&ittedN spaces are re&oved6

    sounde3$% Co&pute the sounde3 encodin* of the strin*6 The strin* 4::: is returned if the

    ar*u&ent is @6 This function is o&itted fro& SQite b+ default6 -t is onl+ available the =

    DSQ-T>ESO@D>X1F co&piler option is used ,hen SQite is built6

    space$n% return space6

    s9liteEversion$U% Return the version strin* for the SQite librar+ that is runnin*6 >3a&ple7 '66:

    substr$N"NZ% Return a substrin* of input strin*that be*ins ,ith the "=th character and ,hich isZ

    characters lon*6 The left=&ost character ofis nu&ber F6 -f "is ne*ative the the first

    character of the substrin* is found b+ countin* fro& the ri*ht rather than the left6 -fis

    strin* then characters indices refer to actual T

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    55/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 55 of *!

    he followin' function will &revent forei'n characters from bein' misinter&reted in te9t. It converts the most common

    &unctuation characters into html e#uivalents.

    function cleantxt($str) {

    $replace = array(

    '&' => '&','"' => '"',

    "'" => ''',

    ';' => ';',

    '' => '>'

    );

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

    return $str;

    }

    Liting 1%.1 B

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    56/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 5 of *!

    Section FG

    Math

    ist of Math

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    57/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 5 of *!

    Math >3a&ples

    Examples

    return the number of rows in the table. (includes NULL values)

    SELECT count(*)AS '# of rows' FROM Testing;# of rows

    ----------

    5

    return the number of rows in table. (does not include NULL values)

    SELECT count(id)AS '# of non NULL values' FROM Testing;

    # of non NULL values

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

    3

    Return average of values. (does not include NULL values)

    SELECT avg(cost)AS 'Average price' FROM Cars;

    Average price----------------

    88528.1666666667

    Return the sum()of values. (does not include NULL values)

    SELECT sum(OrderPrice) AS Sum FROM Orders;

    Sum

    ----------

    4930

    // add columns from two databases or tables, note: as is required

    $result=$db->query('SELECT SUM(Total) -- SUM pulls total values

    FROM (

    SELECT SUM(smith) as Total FROM main.sales -- as is required so sum can pull valuesUNION

    SELECT SUM(smith) as Total FROM lastyear.sales

    )');

    Returnmaximumvalue of a column value

    SELECT max(cost)FROM t1;

    max(cost)

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

    3500

    Returnminimumvalue of a column value

    SELECT min(cost)FROM t1;

    min(cost)

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

    750

    Return randomnumber

    SELECT random()AS Random;

    Random

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

    1056892254869386643

    Mone+

    "#lite does not su&&ort any s&ecial currency format. ou can use inte'er =1+.!!> or *-byte floatin' &oint number

    =1+. with 15 si'nificant di'its.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    58/80

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    59/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 57 of *!

    Savin* an -&a*e

    o save an ima'e, we need to have a s&ecial data ty&e called a blob. blobis a si'nal to the database en'ine that it

    should not try to fi'ure out what the data is for e9am&le it is not a strin' with line ends. Aecause a database does not

    Hnow what ty&e of information is in a blob, we have to Hee& tract of what it is. /e should always have a field that Hee&s

    the media content ty&e =&n', F&', 'if, video, sound, etc>. /e will need this ima'e ty&e later so we can dis&lay it.

    ?or this sam&le &ro'ram we Hnow what the ima'e is. ?or sim&licity saHe we dont show the ste&s needed to retrieve the

    content t+peinformation. he content t+pefield is created in this e9am&le for 'ood &ractice. @ere is an e9am&le of how atable mi'ht looH for someone savin' &hoto'ra&hs.

    # 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: $query);

    Liting 13.5 B

    /ith a table &ro&erly desi'ned, we can now save the data. ?or our e9am&le we assume that the &icture is a pn*filenamed .test6pn*/6/e must use obFect oriented &ro'rammin' and a transaction =e9&lained later> to do our worH.

    # insert row of data to table

    $stmt=$db->prepare(insert into sample (id, description, contenttype, imagedata)

    values (?,?,?,?));

    # assign data for each field

    $id =NULL;

    $describe =Sample image file; # row data

    $type =image/png;

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

    # build the transaction for each field

    $stmt->bindParam(1,$id);

    $stmt->bindParam(2,$describe);

    $stmt->bindParam(3,$type);

    $stmt->bindParam(4,$imagefile,PDO::PARAM_LOB);

    # perform transaction

    $db->beginTransaction(); # create transaction

    $stmt->execute(); # do it

    $db->commit(); # finished

    Liting 13.3 B

    hats itG he data with ima'e has been saved.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    60/80

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    61/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 1 of *!

    echo"connecting...
    ";}

    catch(PDOException $e){echo$e->getMessage()." Error: $query";}

    # enhanced errors

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

    # 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: $query");

    echo"new table and data initialized...
    ";

    # setup transaction to insert row of data to table,

    $stmt=$db->prepare("insert into sample (id, description, contenttype, imagedata) values(?,?,?,?)");

    $id =NULL;

    $describe ="Sample image file";

    $type ="image/png";

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

    # perform transaction

    $stmt->bindParam(1,$id);

    $stmt->bindParam(2,$describe);

    $stmt->bindParam(3,$type);

    $stmt->bindParam(4,$imagefile,PDO::PARAM_LOB);

    $db->beginTransaction(); # create transaction

    $stmt->execute(); # do it

    $db->commit(); # finished

    echo"data saved...
    ";

    # retrive row of data

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

    $result=$db->query($query); # get row of data

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

    $image =$row['imagedata'];

    echo"data retrieved...

    ";

    # save image data to file

    file_put_contents("temp.png",$image);

    # show data

    echo"
    ";

    echo"Fig-1 ".$row['description']."
    ";

    # close db, PHP will also do this automatically

    $db=NULL;

    ?>

    Liting 13.* B

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    62/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' of *!

    :nd of "ection

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    63/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' + of *!

    Section = FJ

    Cr+ptN HashN etc

    M05

    md5Chmac=Hey, data 4, binary4> @M%-M05

    md5Ccry&t=&ass, salt 4, binary4> A"0 com&atible M05 cry&t

    a&rCcry&t=&ass, salt 4, binary4> &ache com&atible M05 cry&t

    sha1=data 4, binary4> "@1

    sha1Chmac=Hey, data 4, binary4> @M%-"@1aesCencry&t=Hey, data 4, binary4> ": encry&tion

    aesCdecry&t=Hey, data 4, binary4> ": decry&tion

    blowfishCencry&t=Hey, data 4, binary4> Alowfish encry&tion

    blowfishCdecry&t=Hey, data 4, binary4> Alowfish decry&tion

    desCencry&t=Hey, data 4, binary4> 0:" encry&tion

    desCdecry&t=Hey, data 4, binary4> 0:" decry&tion

    base Aase< encode

    base Aase< decode

    com&ress=data 4, binary4> com&ress data by Ki&

    decom&ress=data 4, binary4> decom&ress data by Ki&

    uuid=>

    Liting 1.1 B

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    64/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' < of *!

    Appendi3 = A

    >rror Handlin*

    >rror Codes

    The error co%es for S"!ite ersion are unchange% from ersion *.They are as follows+

    O, - Successful resultO / S"! error or missing %atabase$0T0#! * #n internal logic error in S"!ite

    P1 #ccess 2ermission %enie%#3OT 4 Callback routine re5ueste% an abort

    36S7 8 The %atabase file is locke%!OC,D 9 # table in the %atabase is locke%0O11 : # malloc() faile%

    #DO0!7 ; #ttem2t to write a rea%only %atabase$0T6PT < O2eration terminate% by s5lite=interru2t()

    $O /- Some kin% of %isk $>O error occurre%CO6PT // The %atabase %isk image is malforme%0OT?O60D /* ($nternal Only) Table or recor% not foun%

    ?6!! / $nsertion faile% because %atabase is fullC#0TOP0 /4 6nable to o2en the %atabase file

    POTOCO! /8 Database lock 2rotocol error1PT7 /9 ($nternal Only) Database table is em2tySC'1# /: The %atabase schema change%

    TOO3$@ /; Too much %ata for one row of a tableCO0ST#$0T /< #bort %ue to constraint iolation

    1$S1#TC' *- Data ty2e mismatch1$S6S */ !ibrary use% incorrectly0O!?S ** 6ses OS features not su22orte% on host

    #6T' * #uthoriAation %enie%OW /-- s5lite=ste2() has another row rea%y

    DO0 /-/ s5lite=ste2() has finishe% eBecuting

    F% -< LO COP->D COD> O< TH-S R>R>@C>

    If you co&ied and &asted code from this M" /ord document. Ae forewarned that it trans&oses strai'ht ticHs =S>,

    a&ostro&hes ], and #uotes =TT> into forward and reverse versions which are incom&atible with the )@) &arser. I have

    made an attem&t to remove as many as &ossible, but a few may lin'er.

    full set of &roven routines should have accom&anied this document.

    '% SOM> SQ-T> (>RS-O@S HA(> -@COMPAT-0--T->S

    N:L 0atabases are unsu&&orted between +.1.9 and +..9 versions of "2$ite.

    fileCformat 1 3ersion +.!.!.

    fileCformat 3ersion +.1.+.

    fileCformat + 3ersion +.1.

  • 8/11/2019 eBook SQlite, PHP Dan PDO

    65/80

    NeatInfo.com - by Jan Zumwalt Revised March 15, !1

    "#$ite Reference %o&yri'ht ( !!5-!1)' 5 of *!

    ty&ical error is somethin' liHe this, Tmalformed database schema - unable to o&en a database fileOQ

    !% -@(A-D R>SORC> >RROR

    If you 'et an error re&ortin' Tinvalid resourceT when attem&tin' a #uery on a database table and loo&in' throu'h it,the version of the "2$ite e9tension com&iled in to )@) mi'ht be incom&atible with the version that was used to

    create the database =liHe "2$ite .9 vs +.9>.

    he database mi'ht o&en =connect> oH, but will fail when #ueryin'.

    Ddb X new )0=Ss#liteLtm&foo.dbS> success

    foreach =Ddb-\#uery=S":$:% Y ?RM barS> as Drow> &rints invalid resource

    G% S>@S-T-(-TL TO #H-T> SPAC>

    In certain circumstances white s&ace can cause errors, be carefulG

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

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

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

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

    Correct -> ")

    Error -> " )

    I% .@A0> TO OP>@ /

    If you receive an error while tryin' to write to a s#lite database =u&date, delete, dro&>L

    Warning: PDO::query() [function.query]: SQLSTATE[HY000]: General error: 1 unable to open database.

    # uni= 4tem ma4 a/e folder or file permiion pro7lem. he folder containin' the database file must be writeable.

    J% .SQ-T>ECO