You are on page 1of 4

Databases and PHP

Class held on February 10, 2011. Student notes are available on this page. Questions are available
on this page.

At beginning of class
1. Some of you will find this lab difficult.
2. It is part of your next homework
1. But I will give you an automatic extension if you see me in office hours or otherwise get
permission

My notes

SQL Notes

We will be learning little bits of SQL through this class, but we will not be covering SQL in any great level
of detail. For the purposes of today's lab, you will need to know how to perform two basic tasks: inserting
new records and retrieving existing records. To insert a record, the basic syntax is as follows:

INSERT INTO table_name (row_name1, row_name2, row_name3, …) VALUES


(row_1_value, row_2_value, row_3_value, …)

For example, assume you have table named cart with rows for name, description, and price. To
insert a record into that table, you would write:

INSERT INTO cart (name, quantity, price) VALUES ('Widget', 12, 10.00)

Notice that in the VALUES section of the syntax, all text-based entries must be between quotation marks.

That is the level of SQL knowledge that you will need for today's class.

PHP - MySQL connections

Now that we know how to write a little SQL, we need to know how to have PHP connect to the database
and use that SQL. The first step is to have PHP connect to the SQL server. In this case, we will use
MySQL as the SQL server. The command to do this is

$dbc = mysql_connect(address, username, password)

The $dbc is a variable that contains the database connection. You'll use that variable later, so don't
forget about it. For the purposes of this class, we will use the SQL server running on the same computer
as the web server, hence the address is just localhost. The username and password will be provided for
you during class. But if we assume a hypothetical username of jimbob and password
of notarealpassword, then the command is:

$dbc = mysql_connect('localhost', 'jimbob', 'notarealpassword')


Notice that each parameter passed to the function must be enclosed in quotation marks. Single or double
quotes are both fine.

Once you have a connection to the server, you need to access your individual database. Each student
has their own database. The database's name is the same as your NetID. To select this database, use
the mysql_select_db command. The general syntax is:

mysql_select_db(database_name, connection_to_database)

Remember $dbc from earlier? This is the connection_to_database that you'll need. Hence, if your
NetID is bubba and you created a $dbc as described above, then you would enter:

mysql_select_db('bubba', $dbc)

Once you have these steps done, you are ready to start running queries. You only need to do the above
steps once. After you have connected to the database, you can run as many queries as you want using
that one connection. You do not need to repeatedly re-connect to the database within the same script.

PHP - SQL Queries

Now you can put all the pieces together. Using the connection to the SQL server described in the
previous section, you can run the types of queries described in the first section. We'll begin with the
INSERT statements. The first step is to use PHP to generate the INSERT query. Recall our INSERT
statement from the first section:

INSERT INTO cart (name, quantity, price) VALUES ('Widget', 12, 10.00)

Assume that the values are coming from a form with fields named name, quantity, and price. Then we
could have PHP generate that insert statement as follows:

$insert = "INSERT INTO cart (name, quantity, price) VALUES ('" .


$_REQUEST['name'] . "', " . $_REQUEST['quantity'] . ", " .
$_REQUEST['price'] .")";

A couple things to note about this:

 Remember that SQL statements need to have string/text values in quotes. Hence, notice that
the single quotes are still surrounding the name.
 Don't forget to include the ) at the end
 It is often helpful to write the SQL statement out first with dummy values, and then substitute in
the corresponding " . $_REQUEST['parameter_name'] . "  code elements

Once you have your SQL query written, it is time to execute it. This is done with the command:

mysql_query(query_text)

Since we already have a variable with our query text, we can write:

mysql_query($insert)
As a helpful hint, after executing mysql_query, you can use the function mysql_affected_rows() to detect
how many rows were affected by your query. Since you inserted one record, you should find that one row
was affected.

Exercises
Your lab exercise is to store all of your shopping cart entries in a database (we will query the records from
the database next week). When doing this lab DO NOT OVERWRITE YOUR CURRENT CART.PHP
FILE. Create a new file. (Of course you may copy from your existing file.) Otherwise you run the risk of
creating errors and problems with your homework a mere matter of hours before it is due.

You'll have your script connect to the server as described above. In your database, you have a table
named cart. This table is defined as follows:

+---------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+----------------+
| cart_id | int(11) | NO | PRI | NULL | auto_increment |
| text1 | varchar(128) | YES | | NULL | |
| text2 | varchar(128) | YES | | NULL | |
| button | varchar(16) | YES | | NULL | |
| check1 | bit(1) | YES | | NULL | |
| check2 | bit(1) | YES | | NULL | |
| comment | text | YES | | NULL | |
+---------+--------------+------+-----+---------+----------------+

Note that when inserting data, you do not need to insert anything for cart_id. This is an automatically
assigned field that will contain a unique number for each record in the database. (We'll deal with this in
more detail in a future lab.) The remaining fields should correspond to the form fields you were required to
create in your first assignment. The important things to note are the Field column, which tells you the
column name; and the Type column, which tells you the type of data it expects. To translate those types
into more familiar nomenclature:

 int = integer/number
 varchar = text, the number in parentheses is the maximum number of characters
 bit = a 0 or 1
 text = text, no maximum number of characters

Notice that for the two checkboxes, you'll test if the checkbox was checked, and then enter a 0 or 1 into
the database depending on whether it was checked.

With all of this in mind, your lab is to:

1. Have your cart script connect to the database


2. Store the form information into your cart table
3. Display the entries in database to the user

Notice that this means that each time the form is submitted the cart will get another entry and the list of
entries displayed to the user will get longer. We'll talk about removing records in a later lab.

Resources
1. For a quick tutorial on MySQL and PHP, see http://dev.mysql.com/tech-
resources/articles/ddws/21.html

You might also like