Introduction To Databases and SQL
Introduction To Databases and SQL
Databases and
SQL
Files vs Databases
In the last chapter you learned how your PHP scripts can use external files to store
and retrieve data.
Although files do a great job in many circumstances, they're pretty inflexible as data
storage solution.
For example, if you need to filter or sort the data retrieved from a file, you have to
write your own PHP code to do it.
Not only is this tiresome, but if you're working with large sets of data — for example,
hundreds of thousands of user records — your script will probably grind to a halt.
Not good if you're hoping to build a popular Web site.
Databases
Often, the most efficient alternative to text files is to use a database engine —
commonly known as a Database Management System (DBMS) — to store, retrieve,
and modify the data for you.
A good database engine serves as a smart tool between you and your data,
organizing and cataloging the data for quick and easy retrieval.
You can use any database systems in your PHP applications. In this course, you'll
focus on just one database engine: MySQL.
Also, the database model dictates how the data is stored and accessed. Many
different database models are used today but here, we will focus on relational
model, which is the model MYSQL uses.
Relational Databases
In simple terms, a relational database is any database system that allows data to be
associated and grouped by common attributes. For example, a bunch of payroll
records might be grouped by employee, by department, or by date.
Typically, a relational database arranges data into tables, where each table is
divided into rows and columns of data.
Likewise, each column represents a field : a specific type of data that has the same
significance for each record in the table, such as “ first name ” or “ age. ”
Relational Database Example
Here's an example of a database table. Suppose that the manager of a football team
sets up a database so that she can track the matches in which her players compete.
She asks each player to enter his details into the database after each match. After
two matches the manager's table, called matchLog , looks like this:
The Example
In this table, you can see that each row represents a particular set of information
about a player who played on a certain date, and each column contains a specific
type of data for each person or date.
Notice that each column has a name at the top of the table to identify it; this is
known as the field name or column name
Normalization
The manager soon realizes that this matchLog table is going to be huge after
everyone on the team has played an entire season's worth of games.
As you can see, the structure of the table is inefficient because each player's details
(number, name, phone number, and so on) are entered every time he plays a match.
Such redundancy is undesirable in a database. For example, say that the player with
the number 6 keeps dropping the ball, and his teammates decide to give him a new
nickname (which won't be mentioned here). To update the table, every one of this
player's records would have to be modified to reflect his new nickname.
Normalization
By normalizing our data, we can ensure that our data tables are efficient and
well-designed.
This chapter doesn't go into detail about normalization, which is quite a complex
topic. However, the basic idea is to break up your data into several related tables, so
as to minimize the number of times you have to repeat the same data.
The matchLog table contains a lot of repeating data. You can see that most of the
repeating data is connected with individual players. For example, the player with the
nickname “ Witblitz ” is mentioned twice in the table, and each time he ’ s mentioned,
all of his information (his player number, name, and phone number) is also included.
Normalization
Therefore, it makes sense to pull the
player details out into a separate players
table, as follows:
The two tables are said to be joined by the playerNumber field. The playerNumber
field in the matchLog table is known as a foreign key , because it references the
primary key in the players table, and you can't have a playerNumber value in the
matchLog table that isn't also in the players table.
Because the only repeating player information remaining in the matchLog table is
the playerNumber field, you've saved some storage space when compared to the
original table. Furthermore, it's now easy to change the nickname of a player,
because you only have to change it in one place: a single row in the players table.
Talking to Databases with SQL
You're probably wondering how to actually retrieve information from these two
tables, such as the nicknames of the players who played on March 3, 2004.
SQL lets you do practically any database-related task, including creating databases
and tables, as well as saving, retrieving, deleting, and updating data in databases.
MySQL Data Types
When you create a database table — which you do later in this lecture — the type
and size of each field must be defined.
A field is similar to a PHP variable except that you can store only the specified type
and size of data in a given field.
1. numeric
2. date/time
3. string
Numeric Data Types
You can store numbers in MySQL in many ways, but here we will only discuss two of
them:
BIT 0 or 1 0 or 1
You can add the attribute UNSIGNED after a numeric data type when defining a
field. An unsigned data type can only hold positive numbers.
Date and Time Data Types
As with numbers, you can choose from a range of different data types to store dates
and times. Here we only discuss two:
Take a closer look at the FROM and WHERE clauses in the query. The query returns
any record from the users table where the value of the firstName field is “ John".
Assuming there actually is a table called users in the database, the query's output
which is called the result set might look like this:
Simpleton John
Smith John
Thomas John
Setting Up MySQL
The MySQL database system comes with a number of different programs. The two
important ones that you learn about here are:
The MySQL server: This is the database engine itself. The program is usually called
mysqld or similar
The MySQL command-line tool: You can use this tool to talk directly to the MySQL
server so that you can create databases and tables, and add, view, and delete data.
It's handy for setting up your databases and also for troubleshooting. The program
name is simply mysql
Starting the MySQL Server
If you installed WampServer on Windows, or MAMP on Mac OS X, then the MySQL
server and command-line tool should already be installed on your computer.
In fact, MySQL server may already be running, but if it's not, here's how to start it:
To start with, you'll create a very simple table, fruit , containing three fields: id (the
primary key), name (the name of the fruit), and color (the fruit's color).
id is the primary key. It uniquely identifies each row of the table. You created the id field
as INT UNSIGNED , which means it can hold integer values up to 4,294,967,295. You also
specified the keyword AUTO_INCREMENT . This ensures that, whenever a new row is
added to the table, the id field automatically gets a new unique value (starting with 1).
This means you don't have to specify this field's value when inserting data
name will store the name of each fruit. It's created as VARCHAR(30) , which means it can
hold strings of up to 30 characters in length.
color was created in the same way as name , and will be used to store the color of each
fruit.
Adding Data to a Table
To add a new row to a table, you use the SQL INSERT statement. In its basic form, an
INSERT statement looks like this:
This inserts values into each of the fields of the table, in the order that the fields were
created.
Alternatively, you can create a row with only some fields populated. The remaining fields
will contain NULL (if allowed), or in the case of special fields such as an
AUTO_INCREMENT field, the field value will be calculated automatically.
INSERT INTO table ( field1 , field2 , ... ) VALUES ( value1, value2 , ... );
Adding Data to a Table
Now try adding some fruit to your table. you can add three rows to the fruit table by
inserting data into just the name and color fields (the id field will be filled automatically):
id name color
1 banana yellow
2 tangerine orange
3 plum purple
Reading Data From a Table
Or we may use the following statement if we only want to see the name and color of
all fruits.
name color
banana yellow
tangerine orange
plum purple
Reading Data From a Table
Now if we want to retrieve a specific set of records with a given condition we can
add WHERE conditions to our query:
This query will return all records in the fruit table with the name 'banana'
id name color
1 banana yellow
Reading Data From a Table
Similarly we can specify conditions on other fields:
This query will return all records in the fruit table where id >= 2
id name color
2 tangerine orange
3 plum purple
Reading Data From a Table
We can also combine multiple conditions by using AND/OR operators:
Here we will get a record with id >= 2 and the name = 'plum'
id name color
3 plum purple
Updating Data in a Table
You change existing data in a table with the UPDATE statement.
As with the SELECT statement, you can (and usually will) add a WHERE clause to
specify exactly which rows you want to update.
If you leave out the WHERE clause, the entire table gets updated.
UPDATE table SET field1 = value1, field2 = value2, ... WHERE condition;
name of the table you pairs of field name and You can limit the set of
are updating values e.g. age =15 will records that you want
set the age to 15 for all to update by using a
records that the condition. e.g. name =
condition is true 'sally'
Updating Data in a Table
Here's how to use UPDATE to change values in your fruit table:
This SQL statement changes the name and color field values for the record with id =
2. If we read data in the table after this statement, the table looks like this:
id name color
1 banana yellow
2 grapefruit yellow
3 plum purple
Deleting Data from a Table
Deleting works in a similar way to updating.
To delete rows, you use the DELETE statement. If you add a WHERE clause, you can
choose which row or rows to delete; otherwise all the data in the table are deleted
(though the table itself remains)
This will delete one record from our fruit table. We can use SELECT to read data in
our table :
id name color
1 banana yellow
3 plum purple
Deleting Tables
To delete a table entirely, use the DROP TABLE statement
Note that this will delete the table and all records in it. This operation is not
reversible.
Deleting Databases
To delete a database entirely, use the DROP DATABASE statement
Note that this will delete the database and all tables and all records in it. This
operation is not reversible.