Tuesday 6 January 2015

Accessing a SQLite database table from PHP 5.4 upwards

Text in Courier is code to be typed literally
Text in Arial should be substituted for your own values 

<?php

try {
   $file = 'path/to/sqlfile.sl3';  // relative to the directory the php is in 
   $db = new PDO('sqlite:' . $file);  // new php db object, *not* a new db
 } 
catch(PDOException $pe) {
   echo $pe->getMessage();
   exit(0);
 }

try {
   $result = $db->query('SELECT field1,field2,field3,etc FROM table');
   echo '<table>' . "\r\n";
   echo "<tr><th>field1 name</th><th>field2 name</th><th>field3 name</th></tr>\n";
   foreach ( $result as $row ) {
      echo "<tr><td>" . $row['field1'] . "</td>" . 
           "<td>" . $row['field2'] . "</td>" .
           "<td>" . $row['field3'] . "</td>" .
           "</tr>\r\n";
   }
   echo '</table>' . "\r\n";
 } 
catch(PDOException $pe) {
   echo $pe->getMessage();
   exit(0);
 }
?>

No comments:

Post a Comment