PHP and MySQL
John Ryan B. Lorca Instructor I
Introduction to MySQL
SQL is a standard computer language for accessing and manipulating databases. SQL stands for Structured Query Language SQL allows you to access a database SQL is an ANSI standard computer language SQL can execute queries against a database SQL can retrieve data from a database SQL can insert new records in a database SQL can delete records from a database SQL can update records in a database SQL is easy to learn
2
Introduction to MySQL
SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database systems. SQL statements are used to retrieve and update data in a database. SQL works with database programs like MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, etc. Unfortunately, there are many different versions of the SQL language, but to be in compliance with the ANSI standard, they must support the same major keywords in a similar manner (such as SELECT, UPDATE, DELETE, INSERT, WHERE, and others). Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard!
3
SQL links
Tutorials
http://www.w3schools.com/sql/ http://www.sqlzoo.net http://sqlcourse.com (part 2) http://sqlcourse2/com (part 1)
MySQL online reference manual
http://dev.mysql.com/doc/mysql/en/Reference.html
Introduction to MySQL
SQL Database Tables A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. Below is an example of a table called "Persons":
The table above contains three records (one for each person) and four columns (LastName, FirstName, Address, and City).
5
Introduction to MySQL
With SQL, we can query a database and have a result set returned. A query like this: Gives a result set like this:
WARNING
Always assume that everything is case sensitive, especially table names. This is not the case in Windows XP but it is the case in Linux
7
Entering commands (1)
Show all the databases
SHOW DATABASES;
mysql> SHOW DATABASES; +-------------+ | Database | +-------------+ | bookstore | | employee_db | | mysql | | student_db | | test | | web_db | +-------------+
8
Entering commands (2)
Choosing a database and showing its tables
USE test; SHOW tables;
mysql> USE test; Database changed mysql> SHOW tables; +----------------+ | Tables_in_test | +----------------+ | books | | name2 | | names | | test | +----------------+ 4 rows in set (0.00 sec) mysql>
9
Entering commands (3)
Show the structure of a table
DESCRIBE names;
mysql> DESCRIBE names; +-----------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+-------------+------+-----+---------+----------------+ | id | int(11) | | PRI | NULL | auto_increment | | firstName | varchar(20) | | | | | | lastName | varchar(20) | | | | | +-----------+-------------+------+-----+---------+----------------+ 3 rows in set (0.00 sec) mysql>
10
Entering commands (4)
Show the rows of a table (all columns)
SELECT * FROM names;
mysql> SELECT * FROM names; +----+-----------+------------+ | id | firstName | lastName | +----+-----------+------------+ | 1 | Fred | Flintstone | | 2 | Barney | Rubble | +----+-----------+------------+ 2 rows in set (0.00 sec)
mysql>
11
Entering commands (5)
Inserting a new record
INSERT INTO names (firstName, lastName) VALUES ('Rock','Quarry'); SELECT * FROM names;
mysql> INSERT INTO names (firstName, lastName) VALUES ('Ralph', 'Quarry'); Query OK, 1 row affected (0.02 sec) mysql> SELECT * FROM names; +----+-----------+------------+ | id | firstName | lastName | +----+-----------+------------+ | 1 | Fred | Flintstone | | 2 | Barney | Rubble | | 3 | Ralph | Quarry | +----+-----------+------------+ 3 rows in set (0.00 sec) mysql>
12
Entering commands (6)
Updating a record
UPDATE names SET lastName = 'Stone' WHERE id=3; SELECT * FROM names;
mysql> UPDATE names SET lastName = 'Stone' WHERE id=3; Query OK, 1 row affected (0.28 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> SELECT * FROM names; +----+-----------+------------+ | id | firstName | lastName | +----+-----------+------------+ | 1 | Fred | Flintstone | | 2 | Barney | Rubble | | 3 | Ralph | Stone | +----+-----------+------------+ 3 rows in set (0.00 sec) mysql>
13
Database concepts (1)
A relational database management system consists of a number of databases. Each database consists of a number of tables. Example table
column headings
isbn title
books table
author
pub
year
price rows (records)
14
Some SQL data types (1)
Each entry in a row has a type specified by the column. Numeric data types
TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT FLOAT(display_length, decimals) DOUBLE(display_length, decimals) DECIMAL(display_length, decimals)
NUMERIC is the same as DECIMAL
15
Some SQL data types (2)
Date and time types
DATE
format is YYYY-MM-DD
DATETIME
format YYYY-MM-DD HH:MM:SS
TIMESTAMP
format YYYYMMDDHHMMSS
TIME
format HH:MM:SS
YEAR
default length is 4
16
SQL data types (3)
String types
CHAR
fixed length string, e.g., CHAR(20)
VARCHAR
variable length string, e.g., VARCHAR(20)
BLOB, TINYBLOB, MEDIUMBLOB, LONGBLOB
same as TEXT, TINYTEXT ...
ENUM
list of items from which value is selected
17
SQL commands SHOW, USE
SHOW
Display databases or tables in current database; Example (command line client): show databases; show tables;
USE
Specify which database to use Example use bookstore;
18
CREATE creates a database table
Introduction to MySQL Data Definition Language
CREATE TABLE table_name ( column_name1 column_type1, column_name2 column_type2, ... column_nameN column_typeN );
Note: To create a database use the statement CREATE db_name;
19
Introduction to MySQL Data Definition Language
Specifying primary keys
CREATE TABLE table_name ( column_name1 column_type1 NOT NULL DEFAULT '0', column_name2 column_type2, ... column_nameN column_typeN, PRIMARY KEY (column_name1) );
20
Introduction to MySQL Data Definition Language
autoincrement primary integer keys
CREATE TABLE table_name ( column_name1 column_type1 PRIMARY KEY NOT NULL DEFAULT '0' AUTO_INCREMENT, column_name2 column_type2, ... column_nameN column_typeN, );
21
Introduction to MySQL Data Definition Language
Can also create UNIQUE keys. They are similar to PRIMARY KEYS but can have NULL values. Can also create INDEX fields.
22
Introduction to MySQL Data Manipulation Language
SQL Data Manipulation Language (DML) SQL (Structured Query Language) is a syntax for executing queries. But the SQL language also includes a syntax to update, insert, and delete records. These query and update commands together form the Data Manipulation Language (DML) part of SQL:
SELECT - extracts data from a database table UPDATE - updates data in a database table DELETE - deletes data from a database table INSERT INTO - inserts new data into a database table
23
Introduction to MySQL Data Manipulation Language
The SQL SELECT Statement Syntax The SELECT statement is used to select data from a table. The tabular result is stored in a result table (called the result-set).
24
Introduction to MySQL Data Manipulation Language
The SQL SELECT Statement Example To select the content of columns named "LastName" and "FirstName", from the database table called "Persons", use a SELECT statement like this:
The database table "Persons":
The result
25
Introduction to MySQL Data Manipulation Language
Select All Columns To select all columns from the "Persons" table, use a * symbol instead of column names, like this:
Result
26
Introduction to MySQL Data Manipulation Language
The SELECT DISTINCT Statement Syntax The DISTINCT keyword is used to return only distinct (different) values. The SELECT statement returns information from table columns. But what if we only want to select distinct elements? With SQL, all we need to do is to add a DISTINCT keyword to the SELECT statement:
27
Introduction to MySQL Data Manipulation Language
Using the DISTINCT keyword To select ALL values from the column named "Company" we use a SELECT statement like this:
"Orders" table
Results
28
Introduction to MySQL Data Manipulation Language
Using the DISTINCT keyword Note that "W3Schools" is listed twice in the result-set. To select only DIFFERENT values from the column named "Company" we use a SELECT DISTINCT statement like this:
Result
Now "W3Schools" is listed only once in the result-set.
29
Introduction to MySQL Data Manipulation Language
The WHERE Clause - Syntax To conditionally select data from a table, a WHERE clause can be added to the SELECT statement.
With the WHERE clause, the following operators can be used:
Note: In some versions of SQL the <> operator may be written as !=
30
Introduction to MySQL Data Manipulation Language
Using the WHERE Clause To select only the persons living in the city "Sandnes", we add a WHERE clause to the SELECT statement:
"Persons" table
Result
31
Introduction to MySQL Data Manipulation Language
Using Quotes Note that we have used single quotes around the conditional values in the examples. SQL uses single quotes around text values (most database systems will also accept double quotes). Numeric values should not be enclosed in quotes. For text values:
For numeric values:
32
Introduction to MySQL Data Manipulation Language
The LIKE Condition - Syntax The LIKE condition is used to specify a search for a pattern in a column.
A "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.
33
Introduction to MySQL Data Manipulation Language
Using LIKE The following SQL statement will return persons with first names that start with an 'O':
The following SQL statement will return persons with first names that end with an 'a':
The following SQL statement will return persons with first names that contain the pattern 'la':
34
Introduction to MySQL Data Manipulation Language
The INSERT INTO Statement Syntax The INSERT INTO statement is used to insert new rows into a table.
You can also specify the columns for which you want to insert data:
35
Introduction to MySQL Data Manipulation Language
Insert a New Row This "Persons" table:
And this SQL statement:
Will give this result:
36
Introduction to MySQL Data Manipulation Language
The Update Statement Syntax The UPDATE statement is used to modify the data in a table.
Person
37
Introduction to MySQL Data Manipulation Language
Update one Column in a Row We want to add a first name to the person with a last name of "Rasmussen":
Result
38
Introduction to MySQL Data Manipulation Language
Update several Columns in a Row We want to change the address and add the name of the city:
Result
39
Introduction to MySQL Data Manipulation Language
The DELETE Statement Syntax The DELETE statement is used to delete rows in a table.
Person
40
Introduction to MySQL Data Manipulation Language
Delete a Row "Nina Rasmussen" is going to be deleted:
Result
41
Introduction to MySQL Data Manipulation Language
Delete All Rows It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact:
42
Introduction to MySQL Data Manipulation Language
Sort the Rows The ORDER BY clause is used to sort the rows. Orders:
To display the company names in alphabetical order:
Result:
43
Introduction to MySQL Data Manipulation Language
Sort the Rows To display the company names in alphabetical order AND the OrderNumber in numerical order:
Result:
44
Introduction to MySQL Data Manipulation Language
Sort the Rows To display the company names in reverse alphabetical order: Result:
45
Introduction to MySQL Data Manipulation Language
Sort the Rows To display the company names in reverse alphabetical order AND the OrderNumber in numerical order:
Result:
Notice that there are two equal company names (W3Schools) in the result above. The only time you will see the second column in ASC order would be when there are duplicated values in the first sort column, or a handful of nulls.
46
Introduction to MySQL Data Manipulation Language
AND & OR AND and OR join two or more conditions in a WHERE clause. The AND operator displays a row if ALL conditions listed are true. The OR operator displays a row if ANY of the conditions listed are true. Original Table (used in the examples)
47
Introduction to MySQL Data Manipulation Language
AND & OR Use AND to display each person with the first name equal to "Tove", and the last name equal to "Svendson":
Result:
48
Introduction to MySQL Data Manipulation Language
AND & OR Use OR to display each person with the first name equal to "Tove", or the last name equal to "Svendson":
Result:
49
Introduction to MySQL Data Manipulation Language
AND & OR You can also combine AND and OR (use parentheses to form complex expressions):
Result:
50
Introduction to MySQL Data Manipulation Language
IN The IN operator may be used if you know the exact value you want to return for at least one of the columns. Original Table (used in the examples)
51
Introduction to MySQL Data Manipulation Language
IN To display the persons with LastName equal to "Hansen" or "Pettersen", use the following SQL:
Result:
52
Introduction to MySQL Data Manipulation Language
BETWEEN ... AND The BETWEEN ... AND operator selects a range of data between two values. These values can be numbers, text, or dates. Original Table (used in the examples)
53
Introduction to MySQL Data Manipulation Language
BETWEEN ... AND To display the persons alphabetically between (and including) "Hansen" and exclusive "Pettersen", use the following SQL:
Result:
54
Introduction to MySQL Data Manipulation Language
BETWEEN ... AND IMPORTANT! The BETWEEN...AND operator is treated differently in different databases. With some databases a person with the LastName of "Hansen" or "Pettersen" will not be listed (BETWEEN..AND only selects fields that are between and excluding the test values). With some databases a person with the last name of "Hansen" or "Pettersen" will be listed (BETWEEN..AND selects fields that are between and including the test values). With other databases a person with the last name of "Hansen" will be listed, but "Pettersen" will not be listed (BETWEEN..AND selects fields between the test values, including the first test value and excluding the last test value). Therefore: Check how your database treats the BETWEEN....AND operator!
55
Introduction to MySQL Data Manipulation Language
BETWEEN ... AND To display the persons outside the range used in the previous example, use the NOT operator:
Result:
56
PHP and MySQL
<?php // Connecting, selecting database $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') or die('Could not connect: ' . mysql_error()); echo 'Connected successfully'; mysql_select_db('my_database') or die('Could not select database'); // Performing SQL query $query = 'SELECT * FROM my_table'; $result = mysql_query($query) or die('Query failed: ' . mysql_error()); // Printing results in HTML echo "<table>\n"; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "\t<tr>\n"; foreach ($line as $col_value) { echo "\t\t<td>$col_value</td>\n"; } echo "\t</tr>\n"; } echo "</table>\n"; ?>
57