Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Storing Images in MySQL Revisited

Connecting to the Database

Let's now look at some PHP code to connect to the database. We're going to include this in a global PHP script that we'll include from other scripts.

In this code, we first try and connect to the database server. Once that connection is made we try and select our database. If either of these steps fails we output an error message and exit.

Listing 4 Connecting to the database (globals.php)
    $db = mysql_connect('localhost', 'phpriot_demo', 'phpriot123');
    if (!$db) {
        echo "Unable to establish connection to database server";
    if (!mysql_select_db('phpriot_demo', $db)) {
        echo "Unable to connect to database";

We will include this script at the start of every other PHP script used in this article.

In This Article

Bonus listings: 1 available