LAB W W D: Orking ITH Atabases
LAB W W D: Orking ITH Atabases
LAB 11
WORKING WITH DATABASES
Approximate Time
The exercises in this lab should take approximately 120 minutes to complete.
2 Lab 11: Working With Databases
INTRODUCING MYSQL
PREPARING DIRECTORIES
1 If you haven’t done so already, create a folder in your personal drive for all the labs for
this book. This lab (and the next ones as well) requires a functioning webserver and
MySQL installation. This lab assumes you are using easyPHP.
2 From the main labs folder (either downloaded from the textbook’s web site using the
code provided with the textbook or in a common location provided by your instructor),
copy the folder titled lab11 to your course folder created in step one.
If you have finished lab 8, you will likely already have MySQL installed
locally on your development machine, set up on a laboratory web server, or
set up on your web host’s server.
If you are using easyPHP, MySQL will be installed but may not yet be
running. The next exercise will show you how to start MySQL in the
easyPHP environment. If you are using a different installation environment,
you will need to follow the MySQL start up instructions for that
environment.
Figure 11.1 – Accessing MySQL in easyPHP
Although you will be able to manipulate the database from your PHP code,
there are some routine maintenance operations that typically do not
warrant writing custom PHP code. For these types of tasks, we will use a
MySQL management tool. This could be a command line interface (if you
are using Linux and have access to the command line) or the popular web‐
based front‐end phpMyAdmin.
1 Start phpAdmin. In easyPHP, you can do this via the Administration window. If you are
asked to login in, jump to step X.
If you are not asked to login in, then you should see the phpMyAdmin panel as shown in
Figure 11.2. If this is your first time using phpAdmin on your machine, you will likely
need to do steps 2-Y.
2 If this is the first time using MySQL on your machine, you should specify a password for
the MySQL root user before proceeding. To do so, click on the Users link/tab at the top
of the phpAdmin page.
3 From the list of users, click the Edit Privileges link for user root, host 127.0.0.1.
You will see a list of privileges and other information for this user.
4 Scroll down to the login information. And specify a password for the root user. Be sure to
remember yours!! Click the Go button when ready. Return to the main phpMyAdmin
Figure 11.2 – phpMyAdmin
Fundamentals of Web Development 5
Figure 11.3 – Changing maximum upload size
SQL
MySQL, like other relational databases, uses Structured Query Language or,
as it is more commonly called, SQL (pronounced sequel) as the mechanism
for storing and manipulating data. Later in the lab you will use PHP to
execute SQL statements. However you will often find it helpful to run SQL
statements directly in MySQL, especially when debugging.
The following exercises assume that your databases have been created and
populated. They also use phpMyAdmin to run the SQL commands.
Depending on your installation, you may instead be using the command
line.
Fundamentals of Web Development 7
1 In phpMyAdmin, click on the art database, then click on the SQL tab.
You should see the message “Run SQL query/queries on database art:”
4 Return to the SQL window, enter the following new query, and then press Go.
select artworkid, title, yearofwork from artworks
where yearofwork < 1600
This will display just the art works prior to 1600. Notice that in MySQL, a query can be
spread across multiple lines.
5 Modify the query (you can click the Show query box link) as follows and test.
select artworkid, title, yearofwork from artworks
where yearofwork < 1600 order by yearofwork
Figure 11.4 – Exercise 11.4
1 In phpMyAdmin, click on the art database, then click on the SQL tab.
You should see the message “Run SQL query/queries on database art:”
6 Verify the record was updated (i.e, by running the query from step 4).
7 Run the following new query:
delete from artists
Fundamentals of Web Development 9
where lastname = 'Vecchio'
One of the key benefits of databases is that the data they store can be
accessed by queries. This allows us to search a database for a particular
pattern and have a resulting set of matching elements returned quickly. In
large sets of data, searching for a particular record can take a long time. To
speed retrieval times, a special data structure called an index is used. A
database table can contain one or more indexes.
1 In phpMyAdmin, click on the art database, click on the artworks table, and then click on
the Structure tab.
2 In the Structure page, click on the Indexes link.
You will see a list of already-existing indexes. The import script for this database already
has created indexes for the primary key, the foreign keys, and a two other fields.
Figure 11.5 – Creating an index in phpMyAdmin
EXERCISE 11.7 — CREATING USERS IN PHPADMIN
1 In phpMyAdmin, click on the art database, and then click on the Privileges tab.
This will display the users who currently have access to this database. Notice the root
user. This root user has special privileges within MySQL: indeed, you very well may have
logged into phpMyAdmin using the root account.
You are going to create a new user which you will use for subsequent examples in this
lab.
3 In the Add user page, enter the following into the Login information section:
User name (use text filed): testuser
Host (Local): localhost
Password (use text filed): mypassword
Re‐Type: mypassword
You are of course welcome to enter a different user name and password. If you do, you
Fundamentals of Web Development 11
4 In the Database for user section, check the Grant all privileges on database “art”
checkbox.
5 In the Global privileges section, check the five Data privileges (select, insert, update,
delete, and file).
6 Click the Go button.
Figure 11.6 – Creating a user
1 Open config.php and modify the file as follows (if you used different user name and
password in Exercise 11.7, then you will have to change what you enter here).
<?php
define('DBHOST', 'localhost');
define('DBNAME', 'art');
define('DBUSER', 'testuser');
define('DBPASS', 'mypassword');
define('DBCONNSTRING','mysql:host=localhost;dbname=art');
?>
echo '<option value="' . $row['GenreID'] . '">';
echo $row['GenreName'];
echo "</option>";
}
// release the memory used by the result set
mysqli_free_result($result);
}
// close the database connection
mysqli_close($connection);
?>
</select>
</body>
</html>
This uses the procedural mysqli API for accessing databases.
EXERCISE 11.9 — INTEGRATING USER INPUTS (MYSQLI)
</div>
<?php
} // end while
// release the memory used by the result set
mysqli_free_result($result);
} // end if ($result
} // end if (isset
} // end if ($_SERVER
// close the database connection
mysqli_close($connection);
?>
</div>
</div>
The result should look similar to that shown in Figure 11.6. Notice that this type of
coding, in which markup and PHP programming is interspersed, can be quite messy
and tricky to follow. The next exercise will use PHP functions which will minimize the
amount of code that is injected into your markup.
Figure 11.7 – Exercise 11.9 complete
adding the code to display a list of art works whose ArtistId foreign key matches the
selected artist.
3 Modify the following functions to the top of the document (i.e., after the implementation
of outputArtists().
/*
Displays the list of paintings for the artist id specified in the id
query string
*/
function outputPaintings() {
try {
if (isset($_GET['id']) && $_GET['id'] > 0) {
$pdo = new PDO(DBCONNSTRING,DBUSER,DBPASS);
$pdo‐>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'select * from ArtWorks where ArtistId=' . $_GET['id'];
$result = $pdo‐>query($sql);
while ($row = $result‐>fetch()) {
outputSinglePainting($row);
}
$pdo = null;
}
}
catch (PDOException $e) {
die( $e‐>getMessage() );
}
}
/*
Displays a single painting
*/
function outputSinglePainting($row) {
echo '<div class="media">';
echo '<a class="pull‐left" href="#">';
echo '<img class="media‐object" src="images/art/works/square‐medium/'
. $row['ImageFileName'] .'.jpg">';
echo '</a>';
echo '<div class="media‐body">';
echo '<h4 class="media‐heading">';
echo htmlentities($row['Title'], ENT_IGNORE | ENT_HTML5, "ISO‐8859‐1");
echo '</h4>';
echo $row['Description'];
echo '</div>';
echo '</div>';
}
4 Test in browser. The result should be similar to that shown in Figure 11.7.
Note, not all paintings contain a description.
Figure 11.8 – Exercise 11.10 complete
$gallery = $mysqli‐>real_escape_string($_GET['gallery']);
$sql = 'select * from ArtWorks where GalleryId=' . $gallery;
if ($result = mysqli_query($connection, $sql)) {
This provides some protection against injection attacks and other security risks. The
next exercise illustrates a better approach to protecting your sites against SQL injection
attacks.
EXERCISE 11.12 — PREPARED STATEMENTS
/*
Displays a list of genres
*/
function outputGenres() {
try {
$pdo = new PDO(DBCONNSTRING,DBUSER,DBPASS);
$pdo‐>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'select GenreId, GenreName, Description from Genres
Order By Era';
$result = $pdo‐>query($sql);
while ($row = $result‐>fetch()) {
outputSingleGenre($row);
}
$pdo = null;
}
catch (PDOException $e) {
die( $e‐>getMessage() );
}
}
4 Test in browser. The result should look similar to that shown in Figure 11.7. Test the
Fundamentals of Web Development 19
Figure 11.9 – Exercise X.Y complete
The final exercise in this lab is more complicated. It makes use of the ability
within HTML to upload files to a server. In this case, the uploaded files will
then be saved within a BLOB field in a database table and rendered to the
user through a PHP script.
Note: This example assumes that you have already created the travel
database and imported travel.sql.
}
2 Now we will write the function processFileUpload(), which will draw from the solution
you wrote for Exercise 9.8, where we saved the uploaded files to a location on the
server. This time we will use a SQL query to upload the temporary file as a BLOB into the
database.
function processFileUpload(){
$pdo = new PDO(DBCONNSTRING,DBUSER,DBPASS);
$validExt = array("jpg", "png");
$validMime = array("image/jpeg","image/png");
// echo "<pre>";print_r($_FILES);echo "</pre>";
if ($_FILES["inputFile"]["error"] == UPLOAD_ERR_OK) {
$name = $_FILES["inputFile"]["name"];
$extension = end(explode(".", $name));
if (in_array($_FILES["inputFile"]["type"],$validMime) &&
in_array($extension, $validExt)) {
//INSERT INTO BLOB
$fileContent =
file_get_contents($_FILES["inputFile"]['tmp_name']);
$sql = "INSERT INTO travelimage (ImageContent) VALUES(:data)";
$statement = $pdo‐>prepare($sql);
$statement‐>bindParam(':data', $fileContent, PDO::PARAM_LOB);
$statement‐>execute();
echo "file uploaded succesfully";
}
else{
echo "That file extension is not supported";
}
}
}
3 Now you will demonstrate that the file uploaded correctly by adding a link to the newly
uploaded file using an <img> element right after executing the SQL statement.
echo "file uploaded succesfully<br>";
$insertID = $pdo‐>lastInsertId();
//use the ID of the image to create a link to the uploaded image.
echo "<img src='viewImage.php?id=".$insertID."' />";
4 Nice that our image is pointing to a file viewImage.php. You will now create that file and
write code to display the correct image from the database. Create the file
viewImage.php and paste in the code as follows:
<?php
require_once('includes/travel‐config.php');
$pdo = new PDO(DBCONNSTRING,DBUSER,DBPASS);
$sql = "SELECT * FROM travelimage WHERE ImageID=:id" ;
$statement = $pdo‐>prepare($sql);
Fundamentals of Web Development 21
$statement‐>bindValue(':id', $_GET['id']);
$statement‐>execute();
if($row = $statement‐>fetch()) {
// Output the MIME header
header("Content‐type: image/png");
// Output the image
echo ($row["ImageContent"]);
}
?>
Save this code, so that now when you upload a file, that image will be immediately
displayed back to you as shown in Figure 11.9. All database images can now be
accessed so long as we know their ID, using the viewImage.php file.
As an exercise for the reader: To manage multiple types of image files you have to
make some improvements. You would have to change your input filter, add a field to the
table to store the mime type uploaded and then use that field when displaying the
image.
Figure 11.10 Screenshot of the completed form, which uploads and displays files.