Databases and SQL

CSE 190 M (Web Programming) Spring 2008

University of Washington

References: SQL syntax reference, w3schools tutorial

Except where otherwise noted, the contents of this presentation are © Copyright 2008 Marty Stepp, Jessica Miller, and Amit Levy, and are licensed under the Creative Commons Attribution 2.5 License.

Valid XHTML 1.0 Strict Valid CSS!

Lecture outline

Relational database concepts

What is a database, and how does it work?

Relational databases

Why use a database?

Database software

World Database

Countries
code name continent independance_year population gnp head_of_state ...
AFG Afghanistan Asia 1919 22720000 5976.0 Mohammad Omar ...
NLD Netherlands Europe 1581 15864000 371362.0 Beatrix ...
........................

Other columns: region, surface_area, life_expectancy, gnp_old, local_name, government_form, capital, code2

Cities
id name country_code district population
3793New YorkUSANew York8008278
1Los AngelesUSACalifornia3694820
...............
CountriesLanguages
country_codelanguageofficialpercentage
AFGPashtoT52.4
NLDDutchT95.6
............

Structured Query Language (SQL)

the standard language for interacting with a database

SQL basics

SELECT name FROM Cities WHERE id = 17;
INSERT INTO Countries VALUES ('SLD', 'ENG', 'T', 100.0);

The SQL SELECT statement

SELECT column(s) FROM table;
SELECT name, code FROM Countries;
namecode
ChinaCHN
United StatesIND
IndonesiaUSA
BrazilBRA
PakistanPAK
......

Issuing SQL commands directly in MySQL

% mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.

mysql> USE world;
Database changed

mysql> SELECT * from Cities;
+----+----------------+--------------+----------+------------+
| id | name           | country_code | district | population |
+----+----------------+--------------+----------+------------+
|  1 | Kabul          | AFG          | Kabol    |    1780000 |
|  2 | Qandahar       | AFG          | Qandahar |     237500 |
|  3 | Herat          | AFG          | Herat    |     186800 |
|  4 | Mazar-e-Sharif | AFG          | Balkh    |     127800 |
...
+----+----------------+--------------+----------+------------+

The DISTINCT modifier

SELECT DISTINCT column(s) FROM table;
SELECT language
FROM CountriesLanguages;
language
Dutch
English
English
Papiamento
Spanish
Spanish
Spanish
...
SELECT DISTINCT language
FROM CountriesLanguages;
language
Dutch
English
Papiamento
Spanish
...

The WHERE clause

SELECT column(s) FROM table WHERE condition(s);
SELECT name, population FROM Cities WHERE country_code = "FSM";
namepopulation
Weno22000
Palikir8600

More about the WHERE clause

WHERE column operator value(s)
SELECT name, gnp FROM Countries WHERE gnp > 2000000;
codenamegnp
JPNJapan3787042.00
DEUGermany2133367.00
USAUnited States8510700.00
.........

Multiple WHERE clauses: AND, OR

SELECT * FROM Cities WHERE code = 'USA' AND population >= 2000000;
idnamecountry_codedistrictpopulation
3793New YorkUSANew York8008278
3794Los AngelesUSACalifornia3694820
3795ChicagoUSAIllinois2896016
...............

Approximate matches: LIKE

WHERE column LIKE pattern
SELECT code, name, population FROM Countries WHERE name LIKE 'United%';
codenamepopulation
AREUnited Arab Emirates2441000
GBRUnited Kingdom59623400
USAUnited States278357000
UMIUnited States Minor Outlying Islands0

Sorting by a column: ORDER BY

ORDER BY column(s)
SELECT code, name, population FROM Countries
WHERE name LIKE 'United%' ORDER BY population;
codenamepopulation
UMIUnited States Minor Outlying Islands0
AREUnited Arab Emirates2441000
GBRUnited Kingdom59623400
USAUnited States278357000

Using a database in PHP

PHP code on your server that can access database data

Complete PHP MySQL example

# connect to world database on local computer
$db = mysql_connect("localhost", "traveler", "packmybags");
mysql_select_db("world");

# execute a SQL query on the database
$results = mysql_query("SELECT * FROM Countries WHERE population > 100000000;");

# loop through each country
while ($row = mysql_fetch_array($results)) {
?>

	<li> <?= $row["name"] ?>, ruled by <?= $row["head_of_state"] ?> </li>

<?php
}
?>

Connecting to MySQL: mysql_connect

$db = mysql_connect("host", "username", "password");
mysql_select_db("database name");
# connect to world database on local computer
$db = mysql_connect("localhost", "traveler", "packmybags");
mysql_select_db("world");

Performing queries: mysql_query

$db = mysql_connect("host", "username", "password");
mysql_select_db("database name");

$results = mysql_query("SQL query");
...
$results = mysql_query("SELECT * FROM Cities WHERE code = 'USA'
                        AND population >= 2000000;");

Result rows: mysql_fetch_array

$db = mysql_connect("host", "username", "password");
mysql_select_db("database name");
$results = mysql_query("SQL query");

while ($row = mysql_fetch_array($results)) {
	do something with $row;
}

Error-checking: mysql_error

$db = mysql_connect("localhost", "traveler", "packmybags");
if (!$db) {
	die("SQL error occurred on connect: " . mysql_error());
}
if (!mysql_select_db("world")) {
	die("SQL error occurred selecting DB: " . mysql_error());
}
$query = "SELECT * FROM Countries WHERE population > 100000000;";
$results = mysql_query($query);
if (!$results) {
	die("SQL query failed:\n$query\n" . mysql_error());
}

Complete example w/ error checking

# connect to world database on local computer
$db = mysql_connect("localhost", "traveler", "packmybags");
if (!$db) {
	die("SQL error occurred on connect: " . mysql_error());
}
if (!mysql_select_db("world")) {
	die("SQL error occurred selecting DB: " . mysql_error());
}

# execute a SQL query on the database
$query = "SELECT * FROM Countries WHERE population > 100000000;";
$results = mysql_query($query);
if (!$results) {
	die("SQL query failed:\n$query\n" . mysql_error());
}

# loop through each country
while ($row = mysql_fetch_array($results)) {
?>
	<li>
		<?= $row["name"] ?>, ruled by <?= $row["head_of_state"] ?>
	</li>
<?php
}
?>

Other MySQL PHP functions