|[ Team LiB ]|
Adding Data to the Database
You can add name/value pairs to your open database with the function dba_insert(), which requires the name of a key, the value you want to store, and a valid DBA resource (as returned by dba_open()). This function returns true if all is well and false if an error occurs (such as an attempt to write to a database opened in read-only mode, or to overwrite an element of the same name). If the element you are attempting to insert already exists, the data is not overwritten.
Listing 12.1 creates or opens a database called products and adds some data to it.
1: <!DOCTYPE html PUBLIC 2: "-//W3C//DTD XHTML 1.0 Strict//EN" 3: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4: <html> 5: <head> 6: <title>Listing 12.1 Adding Items to a Database</title> 7: </head> 8: <body> 9: <div> 10: 11: Adding products now... 12: 13: <?php 14: $dbh = dba_open( "./data/products", "c", "gdbm" ) 15: or die( "Couldn't open database" ); 16: 17: dba_insert( "Sonic Screwdriver", 23.20, $dbh); 18: dba_insert( "Tricorder", 55.50, $dbh); 19: dba_insert( "ORAC AI", 2200.50, $dbh); 20: dba_insert( "HAL 2000", 4500.00, $dbh); 21: 22: 23: dba_close( $dbh ); 24: ?> 25: </div> 26: </body> 27: </html>
To add values to the database, we use the dba_insert() functions (lines 17–20). All values are converted to strings when added to the database. We can treat our price strings as floats when we extract them from the database, however. We covered the float data type in Hour 4, "The Building Blocks." Notice that we can use keys that have more than one word.
If we now attempt to call dba_insert() with the same key argument as one of the keys we have already used, dba_insert() returns false and makes no change to the database. A warning is also generated. This level of protection prevents accidental data loss. Sometimes, however, you want to overwrite existing data when you write to the database.
|[ Team LiB ]|