O'Reilly logo

Learning PHP, MySQL, and JavaScript by Robin Nixon

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

Rewriting Example 10-8 to Use PEAR

Hopefully you now have the hang of this new object-oriented approach to accessing MySQL. So let’s look at how the sqltest.php program in Example 10-8 can be rewritten using PEAR’s MDB2 package (see Example E-1, sqltest_mdb2.php).

Example E-1. Inserting and deleting using MDB2: sqltest_mdb2.php
<?php // sqltest_mdb2.php
require_once 'login.php';
require_once 'MDB2.php';

$dsn = "mysql://$db_username:$db_password@$db_hostname/$db_database";
$options = array('debug' => 2);
$mdb2 = MDB2::connect($dsn,$options);

if (PEAR::isError($mdb2))
    die("Unable to connect to MySQL: " . $mdb2->getMessage());

if (isset($_POST['author']) &&
    isset($_POST['title']) &&
    isset($_POST['category']) &&
    isset($_POST['year']) &&
    isset($_POST['isbn']))
{
    $author   = get_post('author');
    $title    = get_post('title');
    $category = get_post('category');
    $year     = get_post('year');
    $isbn     = get_post('isbn');

    if (isset($_POST['delete']) && $isbn != "")
    {
        $query = "DELETE FROM classics WHERE isbn='$isbn'";

        if (!$mdb2->query($query))
            echo "DELETE failed: $query<br />" .
            $mdb2->getMessage() . "<br /><br />";
    }
    else
    {
        $query = "INSERT INTO classics VALUES" .
        "('$author', '$title', '$category', '$year', '$isbn')";

        if (!$mdb2->query($query))
            echo "INSERT failed: $query<br />" .
            $mdb2->getMessage() . "<br /><br />";
    }
}

echo <<<_END
<form action="sqltest_mdb2.php" method="post"><pre> Author <input type="text" name="author" /> Title <input type="text" name="title"/ > Category <input type="text" name="category" ...

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