Free2Code
Tutorials » Browse » PHP
Tutorials - Creating a PHP Login Script - Connecting to the database
This article written by
  OldSite

Member since
  October 11, 2006

We need a place to store user information. We need to be able to extract this data to authenticate them and insert new data for new members. This article will use an SQL database for this. We need to design the user database, but first of all we need to connect to the database.

Connecting

We are using the PEAR::DB classes for more portable database coding, rather than using database-specific functions.

File: db_connect.php
<?php

//require the PEAR::DB classes.

require_once 'DB.php';

$db_engine = 'mysql';
$db_user = 'username';
$db_pass = 'password';
$db_host = 'localhost';
$db_name = 'database';

$datasource = $db_engine.'://'.
              $db_user.':'.
              $db_pass.'@'.
               $db_host.'/'.
                $db_name;

$db_object = DB::connect($datasource, TRUE);

/* assign database object in $db_object, 

if the connection fails $db_object will contain

the error message. */

// If $db_object contains an error:

// error and exit.

if(DB::isError($db_object)) {
    die($db_object->getMessage());
}

$db_object->setFetchMode(DB_FETCHMODE_ASSOC);

// we write this later on, ignore for now.

include('check_login.php');

?>

There we have it, that script will create a connection object which we can use in other scripts to do stuff with the database. This script should be put outside your document tree, or in a protected directory to prevent people accessing it directly. There are various things you need to customise.

  • $db_engine – Your database engine, a list of possible values is below.
  • $db_user – Your username to access the database.
  • $db_pass – Your password.
  • $db_host – The host of the database server.
  • $db_name – The name of the database to connect to.

A list of possible database engine values are:

Penguino AVR

Want to learn about robotics or microcontrollers?
Check out the Penguino AVR from our friends at
Icy Labs