Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

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 that 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, then the data is not overwritten.

Listing 11.1 creates or opens a database called products and adds some data to it.

Listing 11.1 Adding Items to a Database

 1: <html>
 2: <head>
 3: <title>Listing 11.1 Adding items to a database</title>
 4: </head>
 5: <body>
 6: Adding products now...
 7: 
 8: <?php
 9: $dbh = dba_open( "./data/products", "c", "gdbm" ) 
10:       or die( "Couldn't open database" );
11: 
12: dba_insert( "Sonic Screwdriver", "23.20", $dbh);
13: dba_insert( "Tricorder", "55.50", $dbh);
14: dba_insert( "ORAC AI", "2200.50", $dbh);
15: dba_insert( "HAL 2000", "4500.50", $dbh);
16: 
17: dba_close( $dbh );
18: ?>
19: </body>
20: </html>

In order to add values to the database we use the dba_insert() functions (lines 12 to 15). All values are converted to strings when added to the database, so we add quotes to the product prices to maintain their format. We can treat these strings as doubles when we extract them from the database if we need to. We covered the double data type in Hour 4 "The Building Blocks." Notice also 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. In some circumstances, this might be what you want; but in others, you will want to amend existing data, as well as create new elements.

  • + Share This
  • 🔖 Save To Your Account