An Introduction To SQL: Kirk Anne
An Introduction To SQL: Kirk Anne
Kirk Anne
Computing & Information Technology
SUNY Geneseo
[email protected]
What is a database?
Parts of a database
• Attributes (fields)
– An attribute or field is a component of a record that
describes something about an item.
• Records
– A record is the representation of an individual item.
• Table
– A collection of records
• Database
– A collection of tables and rules for accessing the
tables
What is a relational database?
• Originally developed by E.F. Codd in 1970
• Organizes data into tables where each
item is a row and the attributes of the item
are in columns.
• Different from “flat file” databases because
you can define “relationships” between
items in different tables.
Parts of a database
Record
Tables
Attribute/Field
• Where most
Joe ABC 123 5532 2234 3211 12345
people start
Jane XYZ 456 3421 14454
(and stop)
Chris PDQ 789 2341 6655 14423
• No room for
growth
• Usually
wastes space
First Normal Form
• Eliminate
repeating columns
Contacts
in each table Id Name Company Address Phone ZipCode
People 3 3211
4 3421
Id Name AddressID
5 2341
1 Joe 1 6 6655
2 Jane 2
3 Chris 3
PhoneRelations
PhoneRelID Id PhoneID
Address 1 1 1
4 2 4
2 XYZ 456 14454
5 3 5
3 PDQ 789 14423
6 3 6
Fifth Normal Form
• The “very esoteric” one that is probably not
required to get the most out of your database.
• “The original table must be reconstructed from
the tables into which it has been broken down.”
• The rule ensures that you have not created any
extraneous columns and all the tables are only
as large as they need to be.
Why normalize?
• Increases the integrity of the data
• Reduces redundancy
• Improves efficiency
• Although normalization can be hard, it is
worth it in the long run.
What do I need to remember?
• Keep normalization in mind.
• Don’t replicate data in a table.
• If you break the rules, know why you are
breaking the rules and do it for a good
reason.
All you need to know about
SQL in 30 minutes (or less)
Basic SQL Commands
• Creating tables with CREATE
• Adding data with INSERT
• Viewing data with SELECT
• Removing data with DELETE
• Modifying data with UPDATE
• Destroying tables with DROP
Creating tables with CREATE
• Generic form
SELECT company,count(company)
FROM contacts
GROUP BY company
HAVING count(company) > 5;
ORDER BY
• The “ORDER BY” clause allows you to
sort the results returned by SELECT.
PHP style
Basic PHP/SQL interaction
1. Open a connection to the database
2. If ok, generate SQL command
3. “Execute” SQL command
4. Handle responses from the server
5. If not done, go back to step 2
6. If done, close connection to database
Creating a table with PHP
<?php
// create a connection with the database
$connection=pg_Connect("host=oracle.geneseo.edu port=5432
dbname=mgmt357 user=mgmt357 password=ecommerce");
// if there is no connection, generate an error and get out
if (!$connection) {
print pg_ErrorMessage(); exit(-1);
};
// Create the table with the pg_exec command
$result=pg_exec($connection,"create table customer (
id int8,
name varchar(50),
address varchar(50),
email varchar(64)
)");
if ($result) {
print "The customer table has been created.";
} else {
print pg_ErrorMessage();
}
pg_close($connection);
?>
Entering data with PHP
<?php pg_close($connection);
} else {
if ($submit) { // display form
// create a connection with the database
?>
$connection=pg_Connect("host=oracle.geneseo.edu
port=5432 dbname=mgmt357 user=mgmt357
password=ecommerce"); <form method="post"
action="<?php echo $PHP_SELF?>">
if (!$connection) { Name: <input type="Text" name="name”>
print pg_ErrorMessage(); Address: <input type="Text" name="address”>
exit(-1); Email:<input type="Text" name="email”>
};
<input type="Submit" name="submit" value="Enter
information”>
$id=time(); // set a unique id number to each record
</form>
$result=pg_exec($connection, "insert into customer
VALUES ($id,'$name','$address','$email')"); <?
}
if ($result) { ?>
print "The customer data has been inserted.<p>";
} else {
print pg_ErrorMessage();
}
Updating data with PHP
<?php pg_close($connection);
} else {
if ($submit) { // display form
// create a connection with the database ?>
$connection=pg_Connect("host=oracle.geneseo.edu port=5432
dbname=mgmt357 user=mgmt357
password=ecommerce"); <form method="post"
action="<?php echo $PHP_SELF?>">
if (!$connection) { Id: <input type=“Text” name=“id”>
print pg_ErrorMessage(); Name: <input type="Text" name="name”>
exit(-1); Address: <input type="Text" name="address”>
}; Email:<input type="Text" name="email”>
<input type="Submit" name="submit" value="Enter information”>
$result=pg_exec($connection, "update customer </form>
set name='$name',
set address='$address',
<?
set email='$email' where id='$id'");
}
?>
if ($result) {
print "The customer data has been inserted.<p>";
} else {
print pg_ErrorMessage();
}
Displaying data with PHP
$result=pg_exec($connection,"select * from customer");
if ($result) {
// get the number of rows and store it in $r
$r = pg_numrows($result);
print "The customer table has $r row(s) of data.<p>";
// set the row counter to the beginning 0
$row=0;
print "<table border=1>\n";
// while there are records to deal with...
while ($data=pg_fetch_object($result,$row)) {
print "<tr>";
print "<td>$data->name</td>";
print "<td>$data->address</td>";
print "<td>$data->email</td>";
print "</tr>\n";
$row++; // increment the counter
};
print "</table>\n";
} else {
print pg_ErrorMessage();
}
Updating data with PHP part 2
<?php pg_close($connection);
} else {
if ($submit) { // display form
// create a connection with the database ?>
$connection=pg_Connect("host=oracle.geneseo.edu port=5432 <form method="post" action="<?php echo $PHP_SELF?>">
dbname=mgmt357 user=mgmt357 <?php
password=ecommerce"); $connection=pg_Connect("host=oracle.geneseo.edu port=5432
dbname=mgmt357 user=mgmt357 password=ecommerce");
if (!$connection) { $result=pg_exec($connection,"select id from customer limit 30");
print pg_ErrorMessage(); $row=0;
exit(-1); print "<select name=id>\n";
}; while ($data=pg_fetch_object($result,$row)) {
print "<option>$data->id\n";
$result=pg_exec($connection, "update customer $row++;
set name='$name', };
set address='$address', print "</select>\n";
set email='$email' where id='$id'"); ?>
Name: <input type="Text" name="name”>
if ($result) { Address: <input type="Text" name="address”>
print "The customer data has been inserted.<p>"; Email:<input type="Text" name="email”>
} else { <input type="Submit" name="submit" value="Enter information”>
print pg_ErrorMessage(); </form>
} <?
}
?>
Getting even easier… PEAR
• Abstracting the database interface
<?php
include('dbinfo.php');
require_once( 'DB.php' );
$db = DB::connect( "mysql://$user:$pass@$host/$dbname" );
// no need to select DB
$sql = 'SELECT * FROM demo';
$demoResult = $db->query($sql);
while ($demoRow = $demoResult->fetchRow()) {
echo $demoRow[2] . '<br>';
}
$db->disconnect();
?>
http://www.phpbuilder.com/columns/allan20010115.php3?page=1
Resources
• PHP Sites
– http://www.php.net
– http://www.phpbuilder.com
– http://www.devshed.com
– http://www.geneseo.edu/~kma/PHP_Intro
• Books
– SQL in a Nutshell, Kevin Kline, O’Reilly
– PostgreSQL: Introduction and Concepts, Bruce
Momjian, Addision Wesley
– Introduction to Database Systems, C.J. Date