Home > Articles > Programming > PHP

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Connecting to the Database

The first step in interacting with a database is to create a connection. When creating the connection, we can assign it to a special type of variable called a resource, as shown in Listing 1.

Listing 1—Connecting to the Database

<?php

//Connect to the database
$connection = mysql_connect ( "localhost", "myusername", "mypassword" );
if ($connection) {
  echo ("Connection created ...");
} else {
  echo ("Error connecting to database!");
}

?>

In this case, we're connecting to a MySQL database, so we'll use mysql_connect(). The three parameters represent the host on which the database is installed (localhost), the appropriate database username (myusername), and its associated password (mypassword).

When making the connection, we usually want to know whether it was created successfully. If not, $connection will be null, so we can create an if-then statement to check for the presence of a connection.

Of course, if the connection wasn't successful, there's not much point in going any further, so it's very common to use a construction more like this, with bold added to emphasize new code:

$connection = mysql_connect ( "localhost", "myusername", "mypassword" )
    || die ( "Error connecting to database!" );

The double pipe (||) represents an or statement, so $connection is looking for the value "connect to the database OR die." A little dramatic, perhaps, but it works because the server will first evaluate the connection statement to see if it needs to go on. If it connects to the database successfully, the OR statement is true, so it doesn't bother seeing what the other condition is. If the connection fails, the server processes the other half of the OR statement—the die() command, which terminates the application (in this case, the page) after outputting the message given as a parameter.

  • + Share This
  • 🔖 Save To Your Account