Connect To Database

If you access the database DIRECTLY through myPHPMyAdmin there no need to connect to it. However, when using a PHP script you have to CONNECT to the database INDIRECTLY. PHP can connect to most databases (e.g., PostgreSQL, SQLite, Sybase) servers. If you use a database that does not have DIRECT support, you will need to use a PHP Open Database Connectivity (ODBC) method with ODBC drivers to connect to a database.

However, we will be using the MySQL server that comes bundle with XAMPP.

Setup Server

Once you create a database and its tables, phpMyAdmin will create a folder with the same name as the database in a server folder. In our case, it is C:/xampp/mysql/data/employee_directory1234 with database related files in it. It is important to remember that data for an application get saved in one folder (e.g., C:/xampp/mysql/data/) while the application get saved in another (e.g., C:/xampp/htdoc/). This is true for all applications that you build.

Before you can connect to a database, you have to first setup a testing or remote server. The process is more involved than creating a static website:

  1. Create a folder in the server's root directory and name it EmployeeDirectory. In our case, this is htdocs folder (e.g., C:\xampp\htdocs\EmployeeDirectory\).
  2. Setup server from within your HTML editor. In Dreamweaver, perform the following steps:
    1. Open up Dreamweaver and select Site > New Site... from the menu
    2. In the dialog box that appears, click on the Site link in the left panel to select it to setup LOCAL FOLDER:
      1. In the Site Name's text field, give the site (app) a name. In our case, Employee Directory.
      2. Click on the folder icon next to the Local Site Folder's text field and navigate to the local site root directory. In our case, it is C:\xampp\htdocs\EmployeeDirectory\ and then click the Select Folder button to enter the path into the Local Site Folder's text field.


    3. Click on the Servers link in the left panel to select it to setup REMOTE OR TESTING FOLDER:
    4. In the screen that appears, click on the plus sign (+) to create a new server.
    5. In the next screen that appears, add or select the following information:
      1. With the Basic tab selected, enter a server name. In our case, Server for Employee Directory.
      2. From the drop down menu next to Connect Using, select Local/Network.

        NOTE: If you are using an ISP, you will need to select an FTP option instead of Local/Network and enter all of the necessary data provided to you by your ISP. You can also click on the Test button to confirm that the remote server connected successfully.

      3. Click on the folder icon next to the Server Folder's text field and navigate to the local server root directory. In our case, it is the same as the site root directory: C:\xampp\htdocs\EmployeeDirectory\.
      4. In the Web URL's text field enter: http://localhost/EmployeeDirectory/.

        NOTE:
        -
        This URL is how you access it from within a browser. You may want to bookmark it so that you have easy access to it.
        CAUTION: It is important to note that the slashes in the path for the Server Folder can be FORWORD OR BACK SLASHES ( \ ) depending on the OS:
        - Mac/UNIX - Forward slash
        - Windows
        - Back slash
        Whereas, the slashes for the Web URL MUST ALWAYS BE FORWARD SLASHES ( / ).



      5. Click on the Advanced tab to select it.
      6. In the Testing Server section, click on the Server Model's drop-down menu and select PHP MySQL.
      7. Click the Save button to save the server settings.


      8. Select the Testing server radio button.

        NOTE: If you have an ISP you may wish to select the Remote server option.


      9. Click the Save button for Site settings.

Connect To Database Server

To establish a connect with the MySQL database, you use the mysql_connect() method that takes at least three arguments and then assign it to a variable (e.g., $db_connection).

SYNTAX: $db_connection = mysql_connect (hostname, username, password);

Once you are through with using the database (e.g., after making a query), it is best practice to close the database connect with the mysql_close() method.

  1. Create a new blank HTML page and save it as connection.php (not .html) in the site root directory (e.g., C:\xampp\htdocs\EmployeeDirectory\).
  2. Write the following PHP code. Comment is optional but recommended.

    <?php 
    // 1. CONNECT to database management system (DBMC) In our case, MySQL.
    $db_connection = mysql_connect("localhost", "CorneliusChopin", "admin");
    ?>

  3. Add the following highlighted code to verified that a database connection was made or not:

    <?php 
    // 1. CONNECT to database management system (DBMC) In our case, MySQL. 
    $db_connection = mysql_connect("localhost", "CorneliusChopin", "admin") or die("Cannot CONNECT to database server");
    print $db_connection;
    ?>

  4. CHECK POINT: Save the file and preview it in a browser. You should see a pointer variable to the connection (e.g., Resource id #3) displayed on the page. This lets you know the connection was made successfully.
  5. Replace the die() method AND the non-informative print statement (print $db_connection;) with an "if" statement to create a custom and more informative message if the database connection is successfully.
    CAUTION: You cannot have the die() method and a custom message at the same time so you HAVE to replace it.

    <?php
    // 1. CONNECT to database management system (DBMC) In our case, MySQL.
    $db_connection = mysql_connect("localhost", "CorneliusChopin", "admin");
    if($db_connection)
    {
      print ("Database server connected successfully.");
    }
    ?>

  6. CHECK POINT: Save the file and preview it in a browser. You should see the message "Database server connected successfully." being displayed on the page.

  7. Add an "else" statement code block below the "if" statement code block to display a message IF the server connection was not successful.

    <?php
    // 1. CONNECT to database management system (DBMC) In our case, MySQL.
    $db_connection = mysql_connect("localhost", "CorneliusChopin", "admin");
    if($db_connection)
    {
      print ("Database server connected successfully.");
    }
    else
    {
    print ("Could not CONNECT to database server.");
    }
    ?>

  8. Temporary change one of the mysql_connect() arguments so that the connection will not be successful. In this case, an X was added to the username.

     $db_connection = mysql_connect("localhost", "CorneliusChopinX", "admin");

  9. CHECK POINT: Save the file and preview in a browser again. You should see a warning message AND the print message that were written to the screen:
    • "Warning: mysql_connect(): Access denied for user..."
    • The print message "Could not CONNECT to database server."

Handle Errors

Getting useful information when an error occurs can save you a lot of debugging time. Instead of getting generic information from your script, you can use the error suppressor operator (@) along with ANY method (e.g., mysql_error(), include()) to display more useful information about errors and warnings. Displaying error messages is good for debugging purposes; however, they should be turned off on a LIVE web site or application.

  1. Add an "@" symbol in front of the $db_connection mysql_connect method:

    $db_connection = @mysql_connect("localhost", "CorneliusChopinX", "admin");

  2. CHECK POINT: Save the file and preview it in a browser again. You should see the previous warning was SUPPRESSED but the custom print message still displays.

    - The @ is an error suppressor operator that can be used in front of any SQL method to suppress any error or warning messages that might be invoked. It is important to note that this operator does not STOP errors from happening but only suppress them from being DISPLAYED so that you can handle the error yourself with some custom error messages as will be done in the next step.

  3. In the "else" code block, modify the print statement to read as follow:

    else
    {
      print ("<p>Could not CONNECT to database server: <br />". mysql_error() . "</p>");
    }

  4. CHECK POINT: Save the file and preview it in a browser again. You should see the custom error message and the sql_error message (See below). The result is a combination of HTML (e.g., <p>, <br />) and PHP (e.g., mysql_error method) that has been "stringed together" with the concatenator operator ( . ). This is similar to not adding the @ to the mysql_connect() method.

    Could not CONNECT to database server:
    Access denied for user 'CorneliusChopinX'@'localhost' (using password: YES)

  5. Remove the temporary change you made to one of the variables and save the file again so the database server connects successfully. In this case, the X was removed but the @ symbol was kept to maintain the custom message:

    $db_connection = @mysql_connect("localhost", "CorneliusChopin", "admin"); 
    // X was removed from CorneliusChopin — don't add this comment

Select A Database

After you make a CONNECTION to a Database Management System (DBMS), the next step is to SELECT a database from the DBMS. Unless it is a new DBMS there is likely more the one database and you have to select one. Before a PHP script can COMMUNICATE (e.g. perform queries on it) with a database, the database must first be SELECTED.

  1. Write the following highlighted code below the first print statement to close the connection:

    <?php
    // 1. CONNECT to database management system (DBMC) In our case, MySQL.
    $db_connection = @mysql_connect("localhost", "CorneliusChopin", "admin");
    if($db_connection)
    {
      print ("Database server connected successfully.");
      // 2. SELECT (NOT CONNECT) to a database from a DBMC
      $db_selection = @mysql_select_db("employee_directory1234");
      // Check if selection was NOT successful 
    if(!$db_selection)
    {
    print("Could not SELECT database");
    }
    } else { /* print ('<p style="color:red; font-weight:bold; text-transform:uppercase">Could not connect to database</p>'); OR */ print ("<p>Could not CONNECT to database server: <br />". mysql_error() . "</p>"); } ?>

  2. CHECK POINT: Save the file and preview it in a browser again. You should see the message "Database server connected successfully." being displayed as before.