Short Intro to PHP and MySQL

Post on 19-May-2015

5,420 views 5 download

Tags:

transcript

SQL, MySQL and PHP

Jussi PohjolainenTAMK University of Applied Sciences

Three-tiered Web Site: LAMPClientUser-agent: Firefox

ServerApache HTTP Server

example requestGET / HTTP/1.1Host: www.tamk.fiUser-Agent: Mozilla/5.0 (Mac..)...

response

DatabaseMySQL

PHPPHP

DATABASES AND SQL

Database Management System( MySQL )Database Management System( MySQL )

DatabaseDatabase

Software for Managing the Database

Software for Managing the Database

QuerysQuerys

Users Users

SQL - Database• SQL – is a database computer language used in relational

databases– Structured Query Language

• ANSI and ISO – standard– SQL-86– SQL-89– SQL-92– SQL-1999– SQL-2003– SQL-2006

• See features:– http://en.wikipedia.org/wiki/Sql#Standardization

SQL - table+----+-----------+-----------+-----------------------+--------------+--------+

| id | firstname | lastname | email | mobile | gender |

+----+-----------+-----------+-----------------------+--------------+--------+

| 0 | Pekka | Virtanen | pekka.virtanen@foo.fi | +35840123456 | m |

| 1 | Tiina | Tampio | tiina.tampio@foo.fi | +35848763324 | f |

| 2 | Kaisa | Kekkonen | kaisa.kekkonen@foo.fi | +35840123456 | f |

| 3 | Pasi | Pesukarhu | pasi.pesukarhu@foo.fi | +358412345 | m |

+----+-----------+-----------+-----------------------+--------------+--------+

Example of Creating Table

CREATE TABLE employees (

id INTEGER,

name VARCHAR(20),

salary DECIMAL(8,2),

PRIMARY KEY (id)

);

Datatypes

• INTEGER• DECIMAL(L,S)• CHAR(N)• VARCHAR(N)• ...

Primary Key

• With primary key you differentiate rows from each other

• Only one primary key for the table

Remove the Table

DROP TABLE employees;

Adding Information to Table

INSERT INTO employees VALUES (

1,

'Jack North',

3000

);

Deleting Information from Table

-- Delete all rows

DELETE FROM employees;

-- Delete one row

DELETE FROM employees

WHERE id = 1;

Retrieving Information

SELECT *

FROM employees;

--

SELECT name, salary

FROM employees;

--

SELECT name

FROM employees

WHERE id = 1;

SELECT *

FROM employees

WHERE id = 1 AND

palkka < 4000;

Multiple Tablesselect * from client;

+----+-----------+-----------+-----------------------+--------------+--------+

| id | firstname | lastname | email | mobile | gender |

+----+-----------+-----------+-----------------------+--------------+--------+

| 0 | Pekka | Virtanen | pekka.virtanen@foo.fi | +35840123456 | m |

| 1 | Tiina | Tampio | tiina.tampio@foo.fi | +35848763324 | f |

| 2 | Kaisa | Kekkonen | kaisa.kekkonen@foo.fi | +35840123456 | f |

| 3 | Pasi | Pesukarhu | pasi.pesukarhu@foo.fi | +358412345 | m |

| 4 | Foo | Bar | foo@bar.baz | +35850505050 | f |

+----+-----------+-----------+-----------------------+--------------+--------+

Multiple Tablesselect * from product;

+----+-------+-------+

| id | name | price |

+----+-------+-------+

| 1 | Milk | 0.70 |

| 2 | Bread | 2.00 |

| 3 | Egg | 1.50 |

+----+-------+-------+

Multiple Tablesselect * from purchase;

+----------+-----------+

| clientID | productID |

+----------+-----------+

| 1 | 1 |

| 2 | 1 |

| 2 | 2 |

+----------+-----------+

3 rows in set (0.00 sec)

Relationshipselect * from client;

+----+-----------+-----------+-----------------------+--------------+--------+

| id | firstname | lastname | email | mobile | gender |

+----+-----------+-----------+-----------------------+--------------+--------+

| 0 | Pekka | Virtanen | pekka.virtanen@foo.fi | +35840123456 | m |

| 1 | Tiina | Tampio | tiina.tampio@foo.fi | +35848763324 | f |

| 2 | Kaisa | Kekkonen | kaisa.kekkonen@foo.fi | +35840123456 | f |

| 3 | Pasi | Pesukarhu | pasi.pesukarhu@foo.fi | +358412345 | m |

| 4 | Foo | Bar | foo@bar.baz | +35850505050 | f |

+----+-----------+-----------+-----------------------+--------------+--------+

select * from product;

+----+-------+-------+

| id | name | price |

+----+-------+-------+

| 1 | Milk | 0.70 |

| 2 | Bread | 2.00 |

| 3 | Egg | 1.50 |

+----+-------+-------+

select * from purchase;

+----------+-----------+

| clientID | productID |

+----------+-----------+

| 1 | 1 |

| 2 | 1 |

| 2 | 2 |

+----------+-----------+

3 rows in set (0.00 sec)

Querymysql> SELECT client.firstname, client.lastname, product.name

-> FROM client, purchase, product

-> WHERE client.id = purchase.clientid AND

-> purchase.productid = product.id;

+-----------+----------+-------+

| firstname | lastname | name |

+-----------+----------+-------+

| Tiina | Tampio | Milk |

| Kaisa | Kekkonen | Milk |

| Kaisa | Kekkonen | Bread |

+-----------+----------+-------+

MYSQL

MySQL

• Very popular SQL-database• Was developed by Swedish company MySQL

AB• In 2008 Sun Microsystems bought MySQL AB– Both GNU GPL and Commercial Licence

• Has different UIs: CLI, WEB and GUI• MySQL is used by Google, Wikipedia and

Yahoo.

MySQL Usage via CLI (TAMK)

• Login to gamma– ssh loginname@tpu.fi

• Login to MySQL– mysql –h myX.tpu.fi –u loginname -p databasename

• See the databases– show databases;

• Change database– use databasename;

• Exit– quit

SSH – connection and MySQL

MySQL Tutorial

• MySQL Tutorial can be found:– http://dev.mysql.com/doc/refman/5.0/en/tutorial.html

PHP AND MYSQL

PHP and MySQL

• PHP has functions that allow access to MySQL Databases

• Access is very easy– 1. Connect– 2. Select Database– 3. Query– 4. Close connection

1. Connect

$link = mysql_connect('mysql_server',

'mysql_user',

'mysql_password');

2. Select Database

$link = mysql_connect('mysql_server',

'mysql_user',

'mysql_password');

$db_selected = mysql_select_db('foo',

$link);

3. Query$link = mysql_connect('mysql_server',

'mysql_user',

'mysql_password');

$db_selected = mysql_select_db('foo',

$link);

$result = mysql_query("DELETE FROM table;", $link);

4. Close$link = mysql_connect('mysql_server',

'mysql_user',

'mysql_password');

$db_selected = mysql_select_db('foo',

$link);

$result = mysql_query("DELETE FROM table;", $link);

mysql_close($link);

mysql_query

• INSERT, UPDATE, DELETE, DROP– Returns true or false

• SELECT, SHOW, DESCRIBE, EXPLAIN– Returns resource on success, false on error– The returned resource should be passed to mysql_fetch_array()

Retrieving Table$link = mysql_connect('mysql_server',

'mysql_user',

'mysql_password');

$db_selected = mysql_select_db('foo',

$link);

$result = mysql_query("SELECT * FROM table;", $link);

while ($row = mysql_fetch_array($result))

{

print($row[0]);

print($row[1]);

}

mysql_close($link);

Retrieving Table$link = mysql_connect('mysql_server',

'mysql_user',

'mysql_password');

$db_selected = mysql_select_db('foo',

$link);

$result = mysql_query("SELECT * FROM table;", $link);

while ($row = mysql_fetch_array($result))

{

print($row["id"]);

print($row["name"]);

}

mysql_close($link);

Retrieving Table$link = mysql_connect('mysql_server',

'mysql_user',

'mysql_password');

$db_selected = mysql_select_db('foo',

$link);

$result = mysql_query("SELECT * FROM table;", $link);

while ($row = mysql_fetch_array($result, MYSQL_BOTH))

{

print($row[0]);

print($row["name"]);

}

mysql_close($link);

Retrieving Table$link = mysql_connect('mysql_server',

'mysql_user',

'mysql_password');

$db_selected = mysql_select_db('foo',

$link);

$result = mysql_query("SELECT * FROM table;", $link);

while ($row = mysql_fetch_array($result, MYSQL_NUM))

{

print($row[0]); // Only number indices

print($row[1]);

}

mysql_close($link);

Retrieving Table$link = mysql_connect('mysql_server',

'mysql_user',

'mysql_password');

$db_selected = mysql_select_db('foo',

$link);

$result = mysql_query("SELECT * FROM table;", $link);

while ($row = mysql_fetch_array($result, MYSQL_ASSOC))

{

print($row["id"]); // Only associative indices

print($row["name"]);

}

mysql_close($link);

Error Handling

• Every function in the previous code examples could fail– Connection can fail, sql query can fail etc.

• Usually you exit the script when DB fails.• With exit($status) – function, you can

stop the execution of the script.

Example of Error Handling 1

$link = mysql_connect('mysql_server',

'mysql_user',

'mysql_password');

if( ! $link )

{

exit("Error connecting to database");

}

Example of Error Handling 2$link = mysql_connect('mysql_server',

'mysql_user',

'mysql_password')

or exit("Error connecting to database");

DESIGNING WEB APPLICATION WITH DB CONNECTION

Maintanence

• Implement app with the point of view of maintanence

• What if the http server is changed?• What if the database server is changed?• What if you have to change the code in your

app?• What if someone else have to change the

code in the app?

Configuration files for DB

• Create special configuration file for Database configuration.

• This file should have constants just for the database connection

• You could name it conf/database.php

Example of conf/database.php<?php/** * database.php - holds necessary constants for database connection * * Copyright information * * Copyright (C) 2008 Jussi Pohjolainen <first.last@tamk.fi> * * License * * Here should be the license... * */

define("MYSQL_HOST", "myX.tpu.fi");define("MYSQL_USER", "pohjus");define("MYSQL_PASSWD", "mypassword");define("MYSQL_DB", "dbpohjus");

// End of file?>

Database Instructions• Create instructions for the admin – How to create the database– How to put example data into the database– Hot to delete the database

• You could create directory just for this:– doc/sql

• install.txt• table-create.sql• table-drop.sql• data-insert.sql• data-delete.sql• select1.sql

table-create.sql-- table-create.sql This will create neccessary clients-table

--

-- COPYRIGHT

-- Copyright information here

-- LICENCE

-- Licence information here

-- DESCRIPTON

-- Detailed description here

CREATE TABLE clients

(

id INTEGER PRIMARY KEY,

firstname VARCHAR(64) NOT NULL,

...

);

-- End of file

install.txtFILE IDENTIFICATION

File : install.txt Time-stamp : <2008-10-17 14:36:53 Jussi Pohjolainen> Description: Database install, test and remove instructions

TO INSTALL THE DATABASE

Database is installed in following steps:

1. ...

EXAMPLE DATA <for testing or product setup>

An example database can be installed in steps:

1. ...

TO REMOVE THE DATABASE

Making Querys

• Create your own class that has Database related methods

• These methods can handles also the errors and exceptions

Example of Usage: lib/include.php<?php

/**

* include.php - file that includes all the necessary files

*

* Copyright information

* Copyright (C) 2008 Jussi Pohjolainen <firstname.lastname@tamk.fi>

*

* License

* License here

*/

// Import basic configuration file

require_once("conf/application.php");

// Import database configuration file

require_once("conf/database.php");

// Import Database - class

require_once("class/Database.php");

// Import Table - class

require_once("class/Table.php");

// Import HTMLGenerator- class

require_once("class/HTMLGenerator.php");

// End of file

?>

Example of Usage: index.php<?php

/**

* index.php – UI for the app

*

* Copyright information + Licence here

*/

// Import all necessary files

require_once("include.php");

function main()

{

print HTMLGenerator::myHeader( TITLE, STYLESHEET );

$result = Database::execute( "select * from clients" );

print Table::toXhtmlTable( $result );

print HTMLGenerator::myFooter();

}

main();

// End of file

?>