Mysql: Eecs 448 Software Engineering Lab Lab #10: Mysql Due Time
Mysql: Eecs 448 Software Engineering Lab Lab #10: Mysql Due Time
MySQL
MySQL is a database language that allows you to create and populate tables that you can then
query in strategic ways. Here the basic hierarchy of a database:
• database
o table
▪ columns of data (each column has a name and a data type)
▪ tuples (a row in the table)
Please see the EECS MySQL reference for more details about the database server. Some important
notes:
• Your DBs are not backed up beyond the scope of this course
• You are capped at 10MB
• You cannot store sensitive information on this server
• You all start with an empty database named the same as your user name
MySQL Shell
Once you enter the MySQL, you'll then have to use valid MySQL shell commands. These are
different than the commands you'll use to interact with the tables in the database. Unfortunately,
awesome things like tab completion isn't available to us, so you'll have to be extra careful when
typing commands. If you're lost, type \h to see a list of options.
Selecting a Database
When working from the command line, you needed to make sure to specify which database you are
going to be working with. The syntax is shown below:
CREATE TABLE
Create is a command that you can use to create a new table in the database. You need to name the
table, define the column names and what type of information each column represents, and what - if
any - keys are in the table.
PRIMARY KEY serves as a unique identifier for each tuple or entry. For example, if you have a table
of citizens, a column for SSN could serve as a primary key.
Here's an example of creating a table called persons that has an SSN as a primary key:
NOTE: If you don't add the ';' at the end of the command, you will need to input the'\g' command
after.
INSERT INTO
You can add entries, or tuples, to a table by using the command INSERT. You have to pick a table
to insert into, the columns you want to insert data into, and the values for each column. When you
insert you are adding a new entry. If you need to update an existing entry, use UPDATE.
Example of add an entry to a table of customers that we assume to exist:
SELECT list-of-column-names
FROM table-name
WHERE criteria
For example, you may have a table of employees and their salaries, and you want to find out who
makes more than $50,000. Select would be great for this.
SELECT emp_name,salary
FROM employees
WHERE salary>50000;
Note: The table might have 10 other columns, but the report we'll get will only keep the name and
salary in view. If you want to see all columns, you can use the wildcard character, '*'.
Example:
SELECT *
FROM employees
WHERE salary>50000;
Notes:
• You can join multiple WHERE clauses using the AND and OR commands
o Example: WHERE salary>50000 AND title='manager'
UPDATE table_name
SET col-name='value'
WHERE col-name='value';
Notes:
• the equal sign operator is used for both comparison in the WHERE clause and assignment
in the SET clause
• You can set multiple values, just separate each assignment by a comma
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste';
JOIN
SQL allows you to join tables in order to gain insight into the information. There are several types of
JOIN:
In this lab, we will use INNER JOIN. INNER JOIN combines two tables based on some criteria, and
the result is a combined listing of all entries from both tables that meet the criteria. In Venn diagram
terms, it yields the intersection of two tables.
W3Schools has a great interactive example of an inner join. Here's the command from the example:
To add some explanation to it, you have two tables, Customers and Orders. The goal is generate a
report that show all customer names and order ids. In short, we are printing a list of all customers
and the ids of the orders they've made. So we SELECT the CustomerName from the Customers
table and the OrdersID from the Orders table, meaning only these columns will show up in the
report. The Customers table does not contain any order ids, nor does the Orders table contain the
customer names. To get a report that has all this data combined, we INNER JOIN Customers with
Orders and the way we match an entry from the Customers table with an entry from the Orders
tables is ON the criteria of the CustomerID from the Customers table matching the CustomerID from
the Orders table.
The ORDER BY clause is entirely optional, but it does help group all the customers together by
name.
Important things to note:
• The syntax of TableName.ColumnName instead of just the ColumnName since the two
tables could have a column of the same name.
• Joining does not alter the tables in any way, it simple generates a report for your viewing
and analysis
order_num customer_id
1 franky97
2 jay321
3 angela31
4 angela31
5 jay321
Note how each order has a unique number, but the foreign key (again, which is a PRIMARY
KEY from the Customers table) can be repeated. The FOREIGN KEY also has the benefit of
preventing us from putting bad data in our Orders table by requiring the entry for customer_id to
exist in the Customers table. In other, we can only make orders for the people listed in our
Customers table.
AUTO INCREMENT
A quick note, for some primary keys you don't really care what the key is as long as it's unique. Take
our Orders table for example. The number doesn't have any meaning beyond just being a unique
identifier for the order. Just like your SSN doesn't have any meaning beyond being a way to uniquely
identify you.
When this occurs, having a PRIMARY that is set to AUTO INCREMENT is very handy. Example.
Other useful commands
• SHOW TABLES
o Display a list of table names
• SHOW COLUMNS FROM table-name
o Show list of columns table-name
• DROP
o USed to remove traits from tables or entire tables.
o Did you read that? A whole table! Gone. Just like that. Be very careful!
o More drop examples
DROP TABLE table_name
• TRUNCATE
o If you want to delete the entries in a table, but not the table itself, essentially
emptying the table.
===mysqli===
PHP has a built in class that handles the interaction with a MySQL database
called mysqli. (Yep, it's a type but doesn't start with a capital letter.
I'll apologize for them.)
<?php
$mysqli = new mysqli("database_URL", "my_user", "my_password",
"database_name");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* close connection */
$mysqli->close();
?>
Explanation:
At construction time, you pass in the URL to the database, your user name, your password (which
should be changed by now!), and the name of the database. Recall that the database you've been
given has the same name as your mysql user name. Next, we see if we were able to connect (e.g.
maybe the network is down, or we misspelled something). We then build a query string; here you are
just writing MySQL code. Then, you send the query to the database. The $result variable is an object
that will contain all the rows of information. The while, goes through one row from the result at a
time.
Where do those array keys come from? Well, those are the column names from your database.
Free dumps the information in $result. Finally we close the connection.
Exercises
Exercise 1: Setup Database
We are going to create a very basic message board system. We will have two tables, Users and
Posts. The users will house the list of users ids. Each user_id will be a unique identifier for a user
and can be a series of characters. Posts will contains the posts the users create. Each post will have
the content, a post_id, and an author_id. The author_id will reference the user_id of whoever wrote
the post. A post_id should be a simple numeric identifier that is automatically chosen by the
database. The content will be a series of text, potentially longer than 255 characters.
The following tables:
• Users
o user_id
• Posts
o post_id
o content
o author_id
All you're doing is create tables. That's it.
Exercise 2: Create User Interface
Files needed:
• CreateUser.html
• CreateUser.php
Using HTML forms again, create a simple frontend that allows the user to create a new user to store
in the database. A simple text field and submit button will do. When the users submits, the backend
should tell the user if the new user was successfully stored in the database.
The new user should not be stored if:
Note: The msqli.query($query) method returns, essentially, false if it does not work.
Exercise 3: Create Posts Interface
Files needed:
• CreatePosts.html
• CreatePosts.php
Create a simple form for the user to give their user name and to write a post. When the user submits
the post, the backend should tell the user if the post was saved or not.
The post should not be saved if:
Administrator Interaction
Required Files Overview:
Exercise 4: AdminHome.html
This should be a series of links to the various administrative pages you will create. You can link
directly to ".php" files.
Exercise 5: ViewUsers.php
Display a table of all users.
Exercise 6: ViewUserPosts
Required Files:
• ViewUserPosts.html
• ViewUserPosts.php
• For this drop down box, you'll need to inject some PHP in your frontend.
When had has chosen a user and clicks submit, the backend will display a table of all the posts that
user has made.
Submission
• Github URL
• people.eecs.ku.edu/~URL
Exercise 7: DeletePost
Bring down the mod hammer!
Required Files: DeletePost.html DeletePost.php
The front end will show a table that has a column of posts, authors, and a column of checkboxes in
with the heading "Delete?".
The admin should then be able to click the boxes of any posts he/she wants to delete. When the
admin clicks submit, all the checked posts should be deleted and a confirmation displaying the post
ids of all the deleted posts.
Rubric
• [15pts] Exercise 1
• [15pts] Exercise 2
• [15pts] Exercise 3
• [5pts] Exercise 4
• [10pts] Exercise 5
• [20pts] Exercise 6
• [20pts] Exercise 7