+ All Categories
Home > Technology > Short Intro to PHP and MySQL

Short Intro to PHP and MySQL

Date post: 19-May-2015
Category:
Upload: jussi-pohjolainen
View: 5,420 times
Download: 5 times
Share this document with a friend
Popular Tags:
48
SQL, MySQL and PHP Jussi Pohjolainen TAMK University of Applied Sciences
Transcript
Page 1: Short Intro to PHP and MySQL

SQL, MySQL and PHP

Jussi PohjolainenTAMK University of Applied Sciences

Page 2: Short Intro to PHP and MySQL

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

Page 3: Short Intro to PHP and MySQL

DATABASES AND SQL

Page 4: Short Intro to PHP and MySQL

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

DatabaseDatabase

Software for Managing the Database

Software for Managing the Database

QuerysQuerys

Users Users

Page 5: Short Intro to PHP and MySQL

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

Page 6: Short Intro to PHP and MySQL

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

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

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

| 0 | Pekka | Virtanen | [email protected] | +35840123456 | m |

| 1 | Tiina | Tampio | [email protected] | +35848763324 | f |

| 2 | Kaisa | Kekkonen | [email protected] | +35840123456 | f |

| 3 | Pasi | Pesukarhu | [email protected] | +358412345 | m |

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

Page 7: Short Intro to PHP and MySQL

Example of Creating Table

CREATE TABLE employees (

id INTEGER,

name VARCHAR(20),

salary DECIMAL(8,2),

PRIMARY KEY (id)

);

Page 8: Short Intro to PHP and MySQL

Datatypes

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

Page 9: Short Intro to PHP and MySQL

Primary Key

• With primary key you differentiate rows from each other

• Only one primary key for the table

Page 10: Short Intro to PHP and MySQL

Remove the Table

DROP TABLE employees;

Page 11: Short Intro to PHP and MySQL

Adding Information to Table

INSERT INTO employees VALUES (

1,

'Jack North',

3000

);

Page 12: Short Intro to PHP and MySQL

Deleting Information from Table

-- Delete all rows

DELETE FROM employees;

-- Delete one row

DELETE FROM employees

WHERE id = 1;

Page 13: Short Intro to PHP and MySQL

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;

Page 14: Short Intro to PHP and MySQL

Multiple Tablesselect * from client;

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

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

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

| 0 | Pekka | Virtanen | [email protected] | +35840123456 | m |

| 1 | Tiina | Tampio | [email protected] | +35848763324 | f |

| 2 | Kaisa | Kekkonen | [email protected] | +35840123456 | f |

| 3 | Pasi | Pesukarhu | [email protected] | +358412345 | m |

| 4 | Foo | Bar | [email protected] | +35850505050 | f |

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

Page 15: Short Intro to PHP and MySQL

Multiple Tablesselect * from product;

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

| id | name | price |

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

| 1 | Milk | 0.70 |

| 2 | Bread | 2.00 |

| 3 | Egg | 1.50 |

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

Page 16: Short Intro to PHP and MySQL

Multiple Tablesselect * from purchase;

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

| clientID | productID |

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

| 1 | 1 |

| 2 | 1 |

| 2 | 2 |

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

3 rows in set (0.00 sec)

Page 17: Short Intro to PHP and MySQL

Relationshipselect * from client;

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

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

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

| 0 | Pekka | Virtanen | [email protected] | +35840123456 | m |

| 1 | Tiina | Tampio | [email protected] | +35848763324 | f |

| 2 | Kaisa | Kekkonen | [email protected] | +35840123456 | f |

| 3 | Pasi | Pesukarhu | [email protected] | +358412345 | m |

| 4 | Foo | Bar | [email protected] | +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)

Page 18: Short Intro to PHP and MySQL

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 |

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

Page 19: Short Intro to PHP and MySQL

MYSQL

Page 20: Short Intro to PHP and 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.

Page 21: Short Intro to PHP and MySQL

MySQL Usage via CLI (TAMK)

• Login to gamma– ssh [email protected]

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

• See the databases– show databases;

• Change database– use databasename;

• Exit– quit

Page 22: Short Intro to PHP and MySQL

SSH – connection and MySQL

Page 23: Short Intro to PHP and MySQL

MySQL Tutorial

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

Page 24: Short Intro to PHP and MySQL

PHP AND MYSQL

Page 25: Short Intro to 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

Page 26: Short Intro to PHP and MySQL

1. Connect

$link = mysql_connect('mysql_server',

'mysql_user',

'mysql_password');

Page 27: Short Intro to PHP and MySQL

2. Select Database

$link = mysql_connect('mysql_server',

'mysql_user',

'mysql_password');

$db_selected = mysql_select_db('foo',

$link);

Page 28: Short Intro to PHP and MySQL

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);

Page 29: Short Intro to PHP and MySQL

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);

Page 30: Short Intro to PHP and MySQL

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()

Page 31: Short Intro to PHP and MySQL

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);

Page 32: Short Intro to PHP and MySQL

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);

Page 33: Short Intro to PHP and MySQL

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);

Page 34: Short Intro to PHP and MySQL

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);

Page 35: Short Intro to PHP and MySQL

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);

Page 36: Short Intro to PHP and MySQL

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.

Page 37: Short Intro to PHP and MySQL

Example of Error Handling 1

$link = mysql_connect('mysql_server',

'mysql_user',

'mysql_password');

if( ! $link )

{

exit("Error connecting to database");

}

Page 38: Short Intro to PHP and MySQL

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

'mysql_user',

'mysql_password')

or exit("Error connecting to database");

Page 39: Short Intro to PHP and MySQL

DESIGNING WEB APPLICATION WITH DB CONNECTION

Page 40: Short Intro to PHP and MySQL

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?

Page 41: Short Intro to PHP and MySQL

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

Page 42: Short Intro to PHP and MySQL

Example of conf/database.php<?php/** * database.php - holds necessary constants for database connection * * Copyright information * * Copyright (C) 2008 Jussi Pohjolainen <[email protected]> * * 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?>

Page 43: Short Intro to PHP and MySQL

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

Page 44: Short Intro to PHP and MySQL

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

Page 45: Short Intro to PHP and MySQL

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

Page 46: Short Intro to PHP and MySQL

Making Querys

• Create your own class that has Database related methods

• These methods can handles also the errors and exceptions

Page 47: Short Intro to PHP and MySQL

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

/**

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

*

* Copyright information

* Copyright (C) 2008 Jussi Pohjolainen <[email protected]>

*

* 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

?>

Page 48: Short Intro to PHP and MySQL

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

?>


Recommended