Article

PHP5: Coming Soon to a Webserver Near You

Page: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Next

Now, to put some data in the table;

   
<?php    
// Insert some data into the table    
   
// Connect to the database    
$sqliteDb='/www/sitepoint/php5/sitepoint.sqlite';    
if ( !$db = sqlite_open($sqliteDb, 0666, $err) )    
   die($err);    
   
// Some data to insert    
$users = array(    
   array(    
       'login'=>'jbloggs',    
       'password'=>md5('secret'),    
       'email'=>'jbloggs@yahoo.com'    
       ),    
   array(    
       'login'=>'jsmith',    
       'password'=>md5('secret'),    
       'email'=>'jsmith@php.net'    
       ) );    
   
foreach ( $users as $user ) {    
   // An INSERT query    
   $sql = "INSERT INTO    
               users (login, password, email)    
           VALUES    
               (    
                   '".$user['login']."',    
                   '".$user['password']."',    
                   '".$user['email']."'    
               )";    
   
   // Perform the query    
   if ( !sqlite_query($sql, $db) )    
       // Die if errors happen, displaying the error message    
       die(sqlite_last_error($db).': '.    
           sqlite_error_string(sqlite_last_error($db)));    
}    
echo ( 'Values inserted successfully' );    
   
// Close connection    
sqlite_close($db);    
?>    

Script: sqlite_insert.php

Because the "id" column is an integer primary key, SQLite handles auto increments for me (like MySQL).

Finally, I select some data from the table;

   
<?php    
// Performs a select on the table    
   
// Connect    
$sqliteDb='/www/sitepoint/php5/sitepoint.sqlite';    
if ( !$db = sqlite_open($sqliteDb, 0666, $err) )    
   die($err);    
   
// Select the data    
$sql = "SELECT    
           *    
       FROM    
           users";    
   
// Get the result    
if ( !$result = sqlite_query($sql, $db) )    
   // Die if errors happen, displaying the error message    
   die(sqlite_last_error($db).': '.    
       sqlite_error_string(sqlite_last_error($db)));    
   
echo ( '<h2>User List</h2>' );    
   
// Fetch the results into an array, row by row    
while ($row = sqlite_fetch_array($result, SQLITE_ASSOC)) {    
   echo ( $row['id'].'. <b>Login:</b> '.$row['login'].    
          ' <b>Email:</b> '.$row['email'].'<br />' );    
}    
   
// Close connection    
sqlite_close($db);    
?>    

Script: sqlite_select.php

It’s pretty simple—more or less the same as working with MySQL in PHP.

As mentioned, SQLite can also store data in memory, which may offer an alternative to PHP's shared memory functions, which have never worked well on Windows. It also has an alternative object oriented API to the PHP functions I used above. See this presentation for more info.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links