CS 199 Willamette University Spring, 2019
 
Programming in PHP, Databases with MySQL,
and Web Applications
 

MySQL Basics with PHP: Connecting, SELECT

PHP provides the capability of connecting with a MySQL database. Once this framework is established, a PHP program can construct SQL queries and then execute the queries on the database. Of course, the interaction of PHP with a database also opens the possibility of embedding database queries within a Web page.

This lab is the first in a series that gradually provides experience with PHP with MySQL.

Making a PHP Connection to a Database

The textbook describes three different approaches that allow PHP to work with MySQL: MySQL, MySQLi (MySQL "improved"), and PDO (PHP Data Objects). Although the first of these is outdated, both of the other approaches are in widespread, active use.

The basic steps for establishing a PDO connection to a database utilizes the following PHP code:

<?php
   // identify details and credentials for accessing the database
   $server   = 'localhost';
   $database = ... ;
   $username = ... ;
   $password = ... ;

   // Establish an environment to report trouble, if a problem occurs
   try {
       $pdo = new PDO("mysql:host=localhost;dbname=$database", $username, $password);    

       // set the PDO error mode to throw exception when run-time error encountered
       $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

       // provide as much protection as possible to counteract possible injection attacks
       $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
   }
   catch (Exception $e) {
       echo "error connecting to $database \n";
       echo "full error message " . $e->getMessage() . "\n";
       echo "exiting\n";
       exit;
   }

   echo "connected to database '$database'\n";

The following notes explain the various steps in this code:

Once a connection is established, one can use SQL queries within the PHP program to work with the database, just as one would in working with a terminal window.

When work with the database is complete (usually at the end of the PHP/HTML page), the connection to the database is closed with the line:

  $pdo = null;

For reference, the first part mysql-pdo-select-1.php shows the code for connection to a database within a complete program.

Initial Steps for the Lab

  1. Copy the above code to your own file. Edit the variable names to indicate your own database and an appropriate username and password. Then save the file on the Web/PHP/MySQL server, and execute it within a Terminal window.

  2. Once your code allows you to make a MySQL connection:

    1. Make an error in the database name, and observe what happens.
    2. Make an error in the username, and observe what happens.
    3. Make an error in the password, and observe what happens.

Often, placing a username and password in every PHP/MySQL file is awkward:

To resolve such troubles, it is common to create a separate file that sets your username and password. For example, a credentials.php file might have the form:

    <?php
      $username = '...';
      $password = '...';

    ?>
  

With this file created, the main PHP/MySQL program can be modified by removing the assignments for $username and $password, and inserting a directive to include the credentials file:

  <?php  
     require "credentials.php";
  ?>
  1. Create your own credentials.php file, insert the appropriate username and password information, replace the username/password lines in the main PHP/MySQL program with a require statement, and check that your program still connects to the database appropriately.

Creating and Executing SELECT Statements

Once a connection is established within a PHP program to a MySQL database, the program can issue and process SQL statements, just as when one is working within a Terminal window. This lab explores two common approaches involving SELECT statements.

Using $pdo->query to Execute the Query

Assuming that a PDO database connection is established, perhaps the simplest way to extract data involves these steps:

Extracting and Displaying a faculty Table

As an example, consider the faculty table from the lab on Getting Starting with a MySQL Database. The first part of that table follows:

  +-----------+---------+------------+------------------+-------------------------+----------+--------+
| facultyID | first   | last       | dept             | email                   | phone    | office |
+-----------+---------+------------+------------------+-------------------------+----------+--------+
|         1 | Haiyan  | Cheng      | Computer Science | hcheng@willamette.edu   | 375-5339 |    207 |
|         2 | Jim     | Levenick   | Computer Science | levenick@willamette.edu | 370-6486 |    206 |
|         3 | Fritz   | Ruehr      | Computer Science | fruehr@willamette.edu   | 370-6165 |    208 |
|         4 | Henry   | Walker     | Computer Science | walker@cs.grinnell.edu  | 375-5314 |    210 |
|         5 | Peter   | Otto       | Mathematics      | potto@willamette.edu    | 370-6487 |    214 |

Within this context, the following code prints the first and last names of each faculty member in the table.

   /* query the database */
   try {
       $sqlQuery = 'SELECT * FROM faculty';
       echo "query:  $sqlQuery \n";
       $result = $pdo->query($sqlQuery);
   }
   catch (Exception $e) {
       echo "error on query:  $sqlQuery \n";
       echo "error message:  $e->getMessage \n";
       echo "exiting \n";
       exit;
   }

   /* report results */
   while ($row = $result->fetch()) {
      echo $row['first'] . " " . $row['last'] . "\n";
   }

Commentary on each part of this code follows:

For reference, the second part mysql-pdo-select-1.php shows the code for this approach to SELECT from a database within a complete program.

More Steps for this Lab

Use the $pdo->query approach in the following steps.

  1. Connect to the faculty database, and print a table of first names, last names, and email addresses for all faculty in the table.

  2. Modify the previous step to print only Mathematics faculty.

  3. Modify the previous step to print only Computer Science faculty whose last names come in the first half of the alphabet.

Using $pdo->prepare and $pd->execute to Execute the Query

When the programmer has full control over the details of an SQL query, the $pdo->query approach can work well. However, consider the following scenario.

An Injection Attack

Suppose a PHP script asks a user to identify a room number, with the intention of retrieving that faculty member from the table. For example, the room number might come from an HTML form. Possible code might have the following form:

  $room = ...
  $query = 'SELECT * FROM faculty where office = ' . $room;

That is, the $query involves the standard SELECT text, and the room number is appended at the end. This approach works fine, if the user types 210 or similar room number. But what if the user enters:

  210 ; DROP TABLE faculty;

Combining these two elements gives the compound SQL statements:

  'SELECT * FROM faculty where office = 210 ; DROP TABLE faculty;

The first part of this is a reasonable SQL query, but the second part erases the entire table! Such a scenario is called an Injection Attack, and such circumstances can undermine much database processing. Of course, if a programmer is writing complete SQL statements, such issues may not arise. However, in many applications, precautions are essential. This type of problem yields an approach to database processing, in which statements are "prepared" before they are executed. The intention is to handle many injection attacks as part of the preparation.

The following code illustrates this cautious approach to SQL queries:

   /* query the database */
   try {
       $query = 'SELECT * FROM faculty where office <= 210';
       echo "query:  $query \n";
       $preparedQuery = $pdo->prepare($query);
       $preparedQuery->execute();
       $result = $preparedQuery->fetchall();
   }
   catch (Exception $e) {
       echo "error on query:  $query \n";
       echo "exiting \n";
       exit;
   }

   /* report results */
   foreach ($result as $row) {
      echo $row['first'] . " " . $row['last'] . "\n";
   }

Again, commentary is needed for the various elements of this code.

For reference, mysql-pdo-select-2.php shows the code for this prepare/execture approach SELECT to a database within a complete program.

Still More Steps: Fun in the Lab Continues

  1. Repeat steps 4, 5, and 6 with this alternative approach for constructing and executing SELECT statements within a PHP program.

  2. Turning to the course table, described in the lab on Changing MySQL Tables,

    1. Write a PHP/MySQL program that retrieves the program, course number, and title of all courses in the table.
    2. Write a PHP/MySQL program that prints all information about the writing courses identified in the table.
    3. Write a PHP/MySQL program that prints the program, course number, and title of all 100-level courses in the table.



created 13 February 2019
revised 15 February 2019
Valid HTML 4.01! Valid CSS!