Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation...

28
Using SQL for online databases A very quick introduction to SQL Data and tables • Normalisation Relational databases The Structured Query Language Using SQL in PHP (with Object Oriented syntax) Common SQL constructs Nic Shulver, FCES, Staffordshire University

Transcript of Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation...

Page 1: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

A very quick introduction to SQL

• Data and tables• Normalisation• Relational databases• The Structured Query Language• Using SQL in PHP (with Object Oriented syntax)• Common SQL constructs

Nic Shulver, FCES, Staffordshire University

Page 2: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

A lot of collected data is repetitive in form

Data may be repetitive in content, too

For example, if we have the following information for 15 people;

[Age in years], [Name], [Height in metres]then we have 15 records of 3 fields, in this format;[whole number], [text], [fractional number]

Ways to structure information

Page 3: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

Here is some simple information:

Danny DeVito(USA), Hugh Jackman (Australia), Halle Berry(USA), Patrick Stewart (UK), …

This kind of information has a simple structure or format

We can put the information into a table

Examples

Page 4: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

No. First Name Last Name Origin

1 Danny DeVito United States of America

2 Arnold Schwarzenegger Austria

3 Halle Berry United States of America

4 Patrick Stewart United Kingdom

5 Karisma Kapoor India

6 Hugh Jackman Australia

7 Alec Guinness United Kingdom

8 Jack Nicholson United States of America

9 Kylie Minogue Australia

Table with repeats

Page 5: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

No. First Name Last Name Origin

1 Danny DeVito 1

2 Arnold Schwarzenegger 2

3 Halle Berry 1

4 Patrick Stewart 3

5 Karisma Kapoor 5

6 Hugh Jackman 4

7 Alec Guinness 3

8 Jack Nicholson 1

9 Kylie Minogue 4

No. Country Name

1 United States of America

2 Austria

3 United Kingdom

4 Australia

5 India

This is an example of a simple one-to-many relationship.

Normalised table

Page 6: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

No. First Name Last Name Origin Films

1 Danny DeVito United States of America Batman Returns

Twins

2 Arnold Schwarzenegger Austria Terminator

True Lies

Twins

Complex Table

Page 7: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

No. First Name Last Name Origin

1 Danny DeVito 1

2 Arnold Schwarzenegger 2

No. Country Name

1 United States of America

2 Austria

3 United Kingdom

4 Australia

5 India

This is an example of several linked tables

No. Films

1 Batman Returns

2 Terminator

1 Hook

1 Twins

2 Twins

Multiple tables…

Page 8: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

The previous example does not solve the problem

What about the other actors/actresses in the films?

Databases can soon get complicated

Need to think carefully about structure before you start – may be difficult later on

For this module, we should only need a few tables (at minimum)

…still too complex?

Page 9: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

Rows and ColumnsBroad view of the table – each row is a record, each column is a

set of fieldsThis is analogous to a spreadsheet view

Records and FieldsDetailed view of the informationEach record (entry) in the database is made up of fields,

possibly with some fields from joined tables

Terminology

Page 10: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

Tables may be joined together – this is very powerful but can get complex

Database systems which allow join relationships are known as Relational Databases (see RDSD)

To build, use and maintain joins between tables, it is often easiest to use tools built into database programs (e.g. MS Access, SQLyog)

Relationships, Joins

Page 11: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

Structured Query Language (SQL), is a set of commands that all programs and users may use to access data within databases

Application programs and tools often allow users to access SQL databases without directly using SQL, but these applications in turn must use SQL when executing the user’s request

Structured Query Language

Page 12: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

SQL provides commands for a variety of tasks including:

querying data,

inserting, updating, and deleting rows in a table,

creating, replacing, altering, and dropping objects,

controlling access to the database and its objects,

guaranteeing database consistency and integrity.

Capabilities

Page 13: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

Why bother with SQL?

SQL gives us the power to access the contents of a database in a simple, powerful way

SQL is (mostly) independent of the underlying database engine

So you can use SQL with many different kinds of databaseThis is simpler than learning how to access each type of

database in a proprietary way

Page 14: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

The restaurant model

• The query engine provides a layer between programming languages and database.• It allows a developer to write programs which access data, without knowing how

the database is implemented.

Page 15: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

// grabs matching record(s) from the “tblstudent" table

$sSQL="SELECT * FROM tblstudent WHERE Email='$sEmail' ";

$rsMain = $mysqli->query($sSQL);

// grabs matching record(s) from the “tblstudent" table

$sSQL="SELECT * FROM tblstudent WHERE Email='$sEmail' ";

$rsMain = $mysqli->query($sSQL);

Example SQL usage in PHP

What does the SQL do?How does PHP use SQL?How does the SQL get sent to the database?Where do the results of the query appear?

Page 16: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

Useful SQL SELECT examples

SELECT lastname, age FROM tblstudent WHERE firstname=‘Naomi’;SELECT * FROM tblstudent WHERE firstname LIKE ‘Naom*’;SELECT * FROM tblstudent WHERE age BETWEEN 16 AND 25;SELECT firstname, studentnumber FROM tblstudent WHERE age>=25;SELECT * FROM tblstudent WHERE studentnumber IS NOT NULL;

Page 17: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

More SQL SELECT examples

SELECT * FROM tblstudent ORDER BY age DESC;SELECT * FROM tblstudent WHERE postcode IN(‘ST1’, ‘ST4’, ‘ST6’);SELECT * FROM tblstudent WHERE age BETWEEN 16 AND 25 ORDER BY age,

studentnumber DESC;SELECT firstname, studentnumber FROM tblstudent WHERE age>=55 AND

studentnumber IS NOT NULL;SELECT COUNT(*) AS “Total” FROM tblstudent WHERE age>=55;

Page 18: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

The Four SQL Statements

There are four main SQL statements you will use.The most useful is SELECT, which we have just seen.It is usually used in this format;SELECT column_name(s) FROM table_name SELECT column_name(s) FROM table WHERE column operator

valuee.g. SELECT lastname, age FROM emp WHERE

firstname=‘Naomi’;

Page 19: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

The Insert Statement

INSERT INTO table_name VALUES (value1, value2,....)Inserts a new row into an existing table INSERT INTO Persons VALUES (‘Lightman', ‘David‘, ‘[email protected]’);INSERT INTO Authorisation VALUES (‘Joshua’, ‘BURGR’);

Insert Data in Specified Columns INSERT INTO Persons (LastName, Address) VALUES (‘Smith', '7 Lee Avenue');

Page 20: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

The Update Statement

UPDATE table_name SET column_name=new_value WHERE column_name=some_value;

Update one Column in a Row:UPDATE Person SET FirstName='Bob' WHERE Email='ab123456';

Update several Columns in a Row: UPDATE Person SET Address='21 Jump Street', City='Los Angeles' WHERE

LastName='Hanson';

Page 21: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

The Delete Statement

DELETE FROM table_name WHERE column_name = some_valueDelete one Row:DELETE FROM Person WHERE Email='ab123456';

Delete several Rows:DELETE FROM Person WHERE LastName='Smith';

Delete all Rows in a Table: [Beware!]DELETE FROM Person;

→ Same as: DELETE FROM Person WHERE LastName='*';

Page 22: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

The Database Connection

Creates a new connection, configured for student ID codes// Note: username is “xy123456”, password is “xy123456”// This is unusual – normally the user, pwd and dbname differ

$id= 'xy123456';$mysqli = new mysqli("web.fcet.staffs.ac.uk", $id, $id, $id);if ($mysqli->connect_errno){ die( "Failed to connect to MySQL: (" .

$mysqli->connect_errno . ") " . $mysqli->connect_error );}

Page 23: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

Using the Statements - Select

// Receives values from Form, assigns values entered to vars$npage_code = $_REQUEST['code'];$sSQL = "SELECT * FROM PageElements WHERE PageCode='$npage_code' ";$rsSearch = $mysqli->query($sSQL);// fetches a row of fields and steps to the next one$row = $rsSearch->fetch_assoc();// gets each field by name$linkcode=$row['LinkAd'];$buycode=$row['BuyAd'];

Page 24: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

Using the Statements - Insert

// Receives values from Form, assigns values entered to vars$formname = $_REQUEST["name"];$formemail = $_REQUEST["email"];$formcomments = $_REQUEST["comments"];// Declares SQL statement that will add data to the database $sSQL = "INSERT INTO users (usrName, usrEmail, usrComments)

VALUES ('$formname', '$formemail', '$formcomments')";// Just runs the SQL query (but better if we checked for errors)$mysqli->query($sSQL);$mysqli->close();

Page 25: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

Using the Statements - Update

// Declares SQL statement that will update a database$sSQL = "UPDATE Members SET FirstName='Mike' WHERE

LastName='North' ";// Executes the SQL…$mysqli->query($sSQL);// note that SELECT, UPDATE, DELETE and INSERT SQL statements all

work with the “query()” method

Page 26: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

Using the Statements - Delete

// Declares SQL statement to delete from a DB$sSQL="DELETE FROM Members WHERE CITY='BELFAST' ";

// Executes the SQL statementIf( !$mysqli->query($sSQL) ){ die("Could not delete from table: " . $mysqli->error);}

Page 27: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

Prepared Statements

• Prepared statements use a template system to avoid SQL injection attacks.

• Example code below – look for the placeholder character$stmt = $mysqli->prepare("SELECT id FROM tblMsgHubUser WHERE tuName=?");$stmt->bind_param("s", $sUser); // s=string$stmt->execute();

Page 28: Using SQL for online databases A very quick introduction to SQL Data and tables Normalisation Relational databases The Structured Query Language Using.

Using SQL for online databases

Conclusion

We have seenWhat SQL can be used for,The value of SQL as a cross-platform database interface

language,Many examples of SQL clauses,Examples of SQL in PHP.http://uk3.php.net/manual/en/class.mysqli.php