O'Reilly logo

Learning PHP 5 by David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Putting Data into the Database

Assuming the connection to the database succeeds, the object returned by DB::connect( ) provides access to the data in your database. Calling that object's functions lets you send queries to the database program and access the results. To put some data into the database, pass an INSERT statement to the object's query( ) function, as shown in Example 7-8.

Example 7-8. Inserting data with query( )

require 'DB.php';
$db = DB::connect('mysql://hunter:w)mp3s@db.example.com/restaurant');
if (DB::isError($db)) { die("connection error: " . $db->getMessage( )); }
$q = $db->query("INSERT INTO dishes (dish_name, price, is_spicy)
    VALUES ('Sesame Seed Puff', 2.50, 0)");

Just like with the $db object that DB::connect( ) returns, the $q object that query( ) returns can be tested with DB::isError( ) to check whether the query was successful. Example 7-9 attempts an INSERT statement that has a bad column name in it. The dishes table doesn't contain a column called dish_size.

Example 7-9. Checking for errors from query( )

require 'DB.php';
$db = DB::connect('mysql://hunter:w)mp3s@db.example.com/restaurant');
if (DB::isError($db)) { die("connection error: " . $db->getMessage( )); }
$q = $db->query("INSERT INTO dishes (dish_size, dish_name, price, is_spicy)
    VALUES ('large', 'Sesame Seed Puff', 2.50, 0)");
if (DB::isError($q)) { die("query error: " . $q->getMessage( )); }

Example 7-9 prints:

query error: DB Error: syntax error

Instead of calling DB::isError( ) after every ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required