(M5-M7) PHP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 96

Applications Development and

Emerging Technologies
MODULE 6

MySQL Database
Objectives
• To provide a good background of Relational Database using
MySQL.
• To know the importance of Database in Web Application using
MySQL.
• To Identify the importance of Database Structure in constructing
tables.
• To be familiar with the syntax in managing users and database.
• To define a good structure of tables in a given database for data
storage.
• To be familiar in the common syntax of creating database and
tables and the correct data type to be used for each field.
Introduction to Databases
• Database – is an ordered collection of information
from which a computer program can quickly access.
• Information stored in computer databases is actually
stored in tables similar to spreadsheet.
• A record in a database is a single complete set of
related information.
• Fields are the individual categories of information
stored in a record.
Example: Employee Directory DB
Fields

last_name first_name address city state zip


Blair Dennis 204 Spruce Lane Brookfield MA 01506
Hernandez Louis 68 Boston Post Road Spencer MA 01562
Miller Erica 271 Baker Hill Road Brookfield MA 01515
Morinaga Scott 17 Ashley Road Brookfield MA 01515
Picard Raymond 1113 Oakham Road Barre MA 01531

Records (Row)

Also called as flat-file database that stores information in a single


table.
Stores information across multiple related tables.
Composed of Primary Table and Related Table (child table)
Primary key is a field that contains a unique identifier for
each record in a primary table.
Foreign key is a field in a related table that refers to the
primary key in a primary table.
Normalization is the process of breaking tables into multiple
related tables to reduce
redundant information.
 One important aspect of database management is its
querying capability.
 A query is a structured set of instructions and criteria for
retrieving, adding, modifying, and deleting database
information.
 Data Manipulation Language (DML) is use for creating
queries.
 Structured Query Language (SQL) has a standard data
manipulation language among many database
management system.
•Either as outgrowths of earlier academic research
(PostgreSQL)

• Developments of lightweight storage tools for websites


(MySQL)

•Open-sourced commercial products (InterBase)


• Most popular open source relational database
• An Australian academician named David Hughes
(Hughes Technologies) wrote a very lightweight
database engine called mSQL (short for mini SQL) -- it
didn't implement a number of features required for full
ANSI SQL certification, but it was very small and very
fast.
• mSQL was distributed as shareware
• incapable of doing a number of essential things -- like
joins
improvement was done by a Swedish programmer Monty
Widenius
MySQL rapidly grew until, although it's still a fast, light
database, it's also a pretty powerful one.
MySQL is written in C++, compiles using GNU gcc, and is
pretty portable -- it has been ported to OS/2, Windows 95 and
NT, as well as a variety of flavours of UNIX
According to the article of Ian Gilfillan in 2004, the
following are the claimed features of MySQL:
• High availability
• High scalability
• High performance
Connecting to MySQL : Console Base
• Console Base
mysql >

• Go to the Command Window


Start\Run
Type command or cmd

• Go to the MySQL path


C:\xampp\mysql\bin\mysql –u root –p
C:\xampp\mysql\bin\mysql –u root
• **Enter password if there is any.
Type commands in MySQL prompt which looks like this:
mysql >
MySQL Log In
MySQL Prompts
Prompt Meaning
mysql> Ready for a new command

-> Waiting for the next line of multiple line command.


‘> Waiting for next line, waiting for completion of a string that
began with single quote (‘ ‘ ‘).
“> Waiting for next line, waiting for completion of a string that
began in double quote (‘ “ ‘).
`> Waiting for next line, waiting for completion of an identifier that
began with a backtick (‘ ` ‘).
/*> Waiting for next line, waiting for completion of a comment that
began with /*.
Example
Basic Commands
• To clear command:
mysql > \c

 Get status from the server:


mysql > status

mysql > \s
Basic Commands
Basic Commands
• Need help?:
mysql > \h

mysql > ?

mysql > \?

mysql > help

 To display the SQL version:


mysql > select version();
Example
Example
Basic Commands
• Display current user:
mysql > select user();

 Display current date:


mysql > select current_date();

 Display today’s date and time:


mysql > select now()
Example
Basic Commands
• To quit
mysql > \q

mysql > quit

mysql > exit


MySQL
Data manipulation Language (DML)
Create, Select, Insert, Update, Delete
Database Creation
Syntax:
CREATE DATABASE <databasename>;
mysql> CREATE DATABASE DBStudent;

Showing and Using the Database:


mysql> SHOW databases;
Syntax: USE <database name>;
mysql> USE DBStudent;

Note: It should display Query OK, 1 row affected as a result.


Example
Table Creation
Syntax:
CREATE TABLE <table name> (field name field type(size)
condition...);

mysql> CREATE TABLE tblStudent(id int(5) primary key


not null auto_increment, name char(25));

Display the structure of the table:


Syntax: DESCRIBE <table name>;
mysql > DESCRIBE tblStudent;
Displaying the list of table:
mysql> SHOW tables;
Sample Screen
Adding of Primary Key
mysql> create table primaryTable (id int not
null auto_increment, name varchar(30),
primary key (id));

mysql> create table keyTable (id int not null


auto_increment, name varchar(30), key (id));

mysql> create table uniqueTable (id int not


null auto_increment, name varchar(30),
unique key (id));
Field Data Types
Type Range Storage
BOOL -128 to 127; 0 is considered false 1 byte
INT or INTEGER -2147483648 to 2147483647 4 bytes

FLOAT A small number with a floating decimal point. 4 bytes


DOUBLE A large number with a floating decimal point. 4 bytes
DATE YYYY-MM-DD Varies
TIME HH:MM:SS Varies
CHAR(m) Fixed length string between 0 to 255 characters Number of bytes
specified by m
VARCHAR(m) Variable length string between 1 to 65,535 Varies according
characters to the number of
bytes specified by
m.
The ‘show’ Command
• This time you can show additional information of a
table
mysql > SHOW COLUMNS FROM tblStudent;

mysql > SHOW TABLE STATUS;

mysql > SHOW TABLE STATUS \G;

mysql > SHOW TABLE STATUS LIKE ‘tblStudent’ \G;

mysql > SHOW CREATE TABLE tblStudent \G;


Example
Example
Modifying the Table Structure
• Adding new column
Syntax: ALTER TABLE <table name> ADD <column
name> <data type(size)>;
mysql > ALTER TABLE tblStudent ADD gender
char(1);
Modifying Table Structure
• Changing Field Type Sizes
Syntax: ALTER TABLE <table name> MODIFY <column
name> <data type(size)>;
mysql > ALTER TABLE tblStudent MODIFY gender
char(7);
Modifying Table Structure
• Changing Field Names
Syntax: ALTER TABLE <table name> CHANGE <column
name> <new column name> <data type(size)>;

mysql > ALTER TABLE tblStudent CHANGE gender


sex char(7);
Modifying Table Structure
• Dropping column
Syntax: ALTER TABLE <table name> DROP <column
name>;
mysql > ALTER TABLE tblStudent DROP sex;
Inserting Values to your Table
Syntax: INSERT INTO <table name> VALUES
(value1, value2, value3, ....);
mysql > INSERT INTO tblStudent VALUES (10001,
‘Juan Dela Cruz’);

To view use ‘SELECT’ command:


Syntax: SELECT * FROM <table name>;
mysql> SELECT * FROM tblStudent;
Example
Inserting Values in a Specific Column
Syntax: INSERT INTO <table name> (column name)
VALUES (value);
mysql> INSERT INTO tblStudent (name) VALUES
(‘Ma. Conchita Borromeo’);
Other Structure
mysql> INSERT INTO tblStudent (id,name) VALUES
(10003,’Mar Roxas’);

mysql> INSERT INTO tblStudent (name,id) VALUES


(’Jojo Binay’,10004);
Updating the Records
Syntax: UPDATE <table name> SET <column name> =
<value> WHERE <column name> = <value>;
mysql> UPDATE tblStudent SET name=‘Ma.
Conchita Dimagiba’ WHERE id=‘10002’;
Updating Multiple Columns
Syntax: UPDATE <table name> SET <column name> =
<value>, <column name> = <value> WHERE <column
name> = <value>;
mysql> UPDATE tblStudent SET name=‘Juan Dela
Peña’, gender=‘M’ WHERE id=‘10001’;
Deleting of Columns
Syntax: DELETE FROM <table name> WHERE <column
name> = <value>;
mysql> DELETE FROM tblStudent WHERE
id=‘10002’;
Deleting all data in a table
Syntax: TRUNCATE TABLE <table name>
or
mysql> TRUNCATE TABLE tblStudent;

mysql> DELETE FROM tblStudent;


To Delete a Table
Syntax: DROP TABLE <table name>;
mysql> DROP TABLE tblStudent;

* You remove a table from the database when it is not required. You
use the DROP TABLE statement to remove a table. When you remove
a table, all the data from the table is also deleted.
To Delete Database
Syntax: DROP DATABASE <database name>;
mysql> DROP DATABASE dbStudent;
Applications Development and
Emerging Technologies
MODULE 5
PHP Web Forms and Form
Validation
PHP Predefined Functions

Objectives
• To apply the available super global variables for form
processing and validation.
• To differentiate the use of $_GET, $_POST, and
$_REQUEST super global variable in form processing and
know when to use it.
• To differentiate the use of Session and Cookies for form
security of a Web Site.
• To know the proper syntax for validating user inputs using
Regular Expression.
Superglobal variables

• $_SERVER
• is an array containing information such as headers, paths, and script
locations.
• entries were created by the web server
• Index ‘PHP_SELF’ contains the filename of the currently executing script.
• $_GET
• an associative array variables passed to the current script via the URL
parameters.
• $_POST
• an associative array of variables passed to the current script via the HTTP
POST method.
Superglobal variables

• $_REQUEST
• an associative array that by default contains the contents of $_GET,
$_POST, and $_COOKIE
• $_COOKIE
• an associative array of variables passed to the current script via HTTP
Cookies
• $_SESSION
• an associative array containing session variables available to the script
• $_ENV
• an associative array of variables passed to the current script via the
environment method
Superglobal variables

Example:
Superglobal variables

Output: before button was clicked Output: submit get button was clicked

Output: submit post button was clicked


Cookies

• are mechanism for storing data in the remote browser and thus tracking or
identifying return users.
• small amount of information containing variable=value pair (user’s
computer).
• users can refuse to accepts cookies.
• Managing cookies can be done using setcookie() function
• syntax: setcookie()
bool setcookie ( string $name [, string $value [, int
$expire = 0 [, string $path [, string $domain [, bool
$secure = false [, bool $httponly = false ]]]]]] )
Cookies

Example: PHPSetCookies.php Output 1: cookies were set

Example: PHPDisplayCookies.php Output 2: after 10 secs

Example: PHPDeleteCookies.php Output 3: delete cookies


Session

• are mechanism for storing data on the server itself.


• is the time that a user spends at your Web site.
• more secure than cookies and can store much more information
• to open a session use session_start() function
• always set at the beginning of each Web page.
• to close the session use session_destroy() function
• gets rid of all the session variable information that’s stored in the session
file.
• the statement does not affect the variables set on the current page.
Session

• to unset session variables use unset() function


• syntax
unset($_SESSION[‘varname’]);

Example: PHPSetSession.php

Example: PHPUnsetSession.php
Session

Example: PHPDisplaySession.php

Example: PHPDeleteSession.php
Session

Output: user load PHPDisplaySession.php page


Output: user clicked the Login link

Output: user clicked the email link

Output: user clicked the logout link


Regular Expression

• were used to efficiently search for patterns in a given text.


• also known as regex or regexp.
• PHP implements Percl Compatible Regular Expression (PCRE)
• PCRE function starts with preg_
• preg_match() function
• Performs a regular expression match
• Syntax: int preg_match ( string $pattern , string
$subject [, array &$matches [, int $flags = 0 [, int
$offset = 0 ]]] )
Regular Expression

Regex Meta Characters

Symbol Description
^ Marks the start of a string
$ Marks the end of a string
. Matches any single character
| Boolean OR
() Group elements
[abc] Item range (a,b or c)
[^abc] Not in range (every character except a,b, or c)
\s white-space character
a? Zero or one ‘a’ character. Equals to a{0,1}
a* Zero or more of ‘a’
Regular Expression

Regex Meta Characters (continue)

Symbol Description
a+ One or more of ‘a’
a{2} Exactly two of ‘a’
a{,5} Up to five of ‘a’
a{5,10} Between five to ten of ‘a’
\w Any alpha numeric character plus underscore. Equals to
[A-Za-z0-9_]
\W Any non alpha numeric characters
\s Any white-space character
\S Any non white-space character
\d Any digits. Equal to [0-9]
\D Any non-digits. Equal to [^0-9]
Regular Expression

Regex Pattern Modifiers

Description
i Ignore Case
m Multiline Mode
S Extra analysis of pattern
u Pattern is treated as UTF-8
Regular Expression

Example

Example Description
‘/hello/’ It will match the word hello
‘/^hello/’ It will match hello at the start of a string. Possible matches
are hello orhelloworld, but not worldhello
‘/hello$/’ It will match hello at the end of a string.
‘/he.o/’ It will match any character between he and o. Possible
matches are heloor heyo, but not hello
‘/he?llo/’ It will match either llo or hello
‘/hello+/’ It will match hello on or more time. E.g. hello or hellohello
‘/he*llo/’ Matches llo, hello or hehello, but not hellooo
‘/hello|world/’ It will either match the word hello or world
‘/(A-Z)/’ Using it with the hyphen character, this pattern will match
every uppercase character from A to Z. E.g. A, B, C…
Regular Expression

Example: (continue)

Example Description
‘/[abc]/’ It will match any single character a, b or c
‘/abc{1}/’ Matches precisely one c character after the characters ab.
E.g. matchesabc, but not abcc
‘/abc{1,}/’ Matches one or more c character after the characters ab.
E.g. matches abcor abcc
‘/abc{2,4}/’ Matches between two and four c character after the
characters ab. E.g. matches abcc, abccc or abcccc, but
not abc
Regular Expression

Useful Regex Functions


Email validation
Applications Development and
Emerging Technologies
MODULE 7

PHP Application with MySQL


Using Group Functions
• Example: SUM
$query = mysql_query(“SELECT SUM(tuition) FROM tblstudent”);
$fetch = mysql_fetch_array($query)

echo $fetch[“SUM(tuition)”]
Using Group Functions
$query = mysql_query(“SELECT SUM(tuition) FROM tblstudent”);
$fetch = mysql_fetch_array($query)

echo $fetch[0]
Using Group Functions
$query = mysql_query(“SELECT SUM(tuition) FROM tblstudent”);
$fetch = mysql_result($query,0);

echo $fetch;
mysql_result()
• mysql_result() retrieves the contents of one cell from a
MySQL result set
• Syntax:
mysql_result($result_query, row, field)
$result_query - The result resource that is being
evaluated. This result comes from a call to mysql_query().
row - The row number from the result that's being retrieved.
Row numbers start at 0.
field - The name or offset of the field being retrieved.
Example: mysql_result()
$query = mysql_query(“SELECT name FROM tblstudent”);
$fetch = mysql_result($query, 2) //gets the 3rd row of name

echo $fetch; // prints the 3rd row of name

$query = mysql_query(“SELECT CONCAT(name,’ ‘,gender) as


Output FROM tblstudent WHERE id=‘200812345’”);
$fetch = mysql_result($query, 0, “Output”)

echo $fetch; // prints the name & gender of the query


Using Group Functions
• Example: MAX
$query = mysql_query(“SELECT MAX(tuition) FROM tblstudent”);
$fetch = mysql_fetch_array($query)

echo $fetch[“MAX(tuition)”]

$query = mysql_query(“SELECT MAX(tuition) FROM tblstudent”);


$fetch = mysql_fetch_array($query)

echo $fetch[0]

$query = mysql_query(“SELECT MAX(tuition) FROM tblstudent”);


$fetch = mysql_result($query,0);

echo $fetch;
Using Group Functions
• Example: MIN
$query = mysql_query(“SELECT MIN(tuition) FROM tblstudent”);
$fetch = mysql_fetch_array($query)

echo $fetch[“MIN(tuition)”]

$query = mysql_query(“SELECT MIN(tuition) FROM tblstudent”);


$fetch = mysql_fetch_array($query)

echo $fetch[0]

$query = mysql_query(“SELECT MIN(tuition) FROM tblstudent”);


$fetch = mysql_result($query,0);

echo $fetch;
mysql_affected_rows()
• mysql_affected_rows() get the number of affected rows
by the last SELECT, INSERT, UPDATE, REPLACE or DELETE query.
• Syntax: mysql_affected_rows()
• Example:

$query = mysql_query(“SELECT id FROM tblstudent WHERE id LIKE


‘%2009%’”);

echo mysql_affected_rows(); // will return the number of rows


matched from the query
mysql_num_rows()
• mysql_num_rows() retrieves the number of rows from a
result set. This command is only valid for statements like SELECT
or SHOW that return an actual result set.
• Syntax: mysql_num_rows()
• Example:

$query = mysql_query(“SELECT id FROM tblstudent WHERE id LIKE


‘%2009%’”);

echo mysql_num_rows(); // will return the number of rows


matched from the query
More MySQL Functions

Visit
➢http://www.php.net/manual/en/ref.mysql.php
➢http://w3schools.com/php/php_ref_mysql.asp
Working with File Uploads
$_FILES
• Using the global PHP $_FILES array you can upload files from a
client computer to the remote server.
• Syntax: $_FILES[“file”][“index”]
file – the name of the field in the form
index – specifies the parameter to be processed by $_FILES
Index Description
name The name of the uploaded file
type The type of the uploaded file
size The size of the uploaded file
tmp_name The name of the temporary copy of the file stored on the server
error the error code resulting from the file upload
Create the upload form
Sample Output
Saving File Permanently
• To save permanently the uploaded file, use the
move_uploaded_file() function. This function returns
TRUE on success, or FALSE on failure.
• Syntax: move_upload_file(file, new location);
• Example:
$destination = ‘uploadedFile’; // folder in your htdocs
$tmp_name = $_FILES[“fileUp”][“tmp_name”];
$filename = $_FILES[“fileUp”][“name”];

move_uploaded_file($tmp_name, “$destination/$filename”);
Example
Example
Validating Files
Function Description Example
file_exists() Checking for file file_exists(“test.txt”)
existence
is_file() Checking if it is a file is_file(“test.txt”)
is_dir() Checking if it is a is_dir(“/tmp”)
directory
is_readable() is_readable(“test.txt”)
is_writable() Checking the file status is_writable(“test.txt”)
is_executable() is_executable(“test.txt”)
filesize() Determining file size filesize(“test.txt”)
Example
<?php
$file = "test.txt";
outputFileTestInfo($file);

function outputFileTestInfo($f) {
if (!file_exists($f)) {
echo "<p>$f does not exist</p>";
return;
}
echo "<p>$f is ".(is_file($f)?"":"not ")."a file</p>";
echo "<p>$f is ".(is_dir($f)?"":"not ")."a directory</p>";
echo "<p>$f is ".(is_readable($f)?"":"not ")."readable</p>";
echo "<p>$f is ".(is_writable($f)?"":"not ")."writable</p>";
echo "<p>$f is ".(is_executable($f)?"":"not ")."executable</p>";
echo "<p>$f is ".(filesize($f))." bytes</p>";
}
?>
touch() - attempts to create an empty file. If the file
already exists, its contents won't be disturbed, but
the modification date will be updated to reflect the
time at which the function executed.
Example: touch(“myfile.txt”);
unlink() – a function used to remove an existing
file.
Example: unlink(“myfile.txt”);
fopen() – is used to open a file for reading, writing or
appending content
Syntax: fopen(“file”, “mode”);
Example:
• fopen(“test.txt”, “r”) – for reading
• fopen(“test.txt”, “w”) – for writing
• fopen(“test.txt”, “a”) – for appending
fclose() – to close a file
Reading Lines from a File
• fgets() – to read a line from a file
• feof() – to tell the last line of a file
$filename = "test.txt";
$fp = fopen($filename, "r") or die("Couldn't open $filename");
while (!feof($fp)) {
$line = fgets($fp, 1024);
echo "$line<br>";
}
Reading Lines from a File
• fread() – to read a specified set of character in a file
• fgetc() – to read a file per character
$filename = "test.txt";
$fp = fopen($filename, "r") or die("Couldn't open $filename");
while (!feof($fp)) {
$chunk = fread($fp, 8);
echo "$chunk<br>"; }
$filename = "test.txt";
$fp = fopen($filename, "r") or die("Couldn't open $filename");
while (!feof($fp)) {
$char = fgetc($fp);
echo "$char<br>"; }
Writing and Appending to a File
• The fwrite() function accepts a file resource and a
string, and then writes the string to the file
• The fputs() function works in exactly the same way.

$filename = "test.txt";
echo "<p>Writing to $filename ... </p>";
$fp = fopen($filename, "w") or die("Couldn't open $filename");
fwrite($fp, "Hello world\n");
fclose($fp);
echo "<p>Appending to $filename ...</p>";
$fp = fopen($filename, "a") or die("Couldn't open $filename");
fputs($fp, "And another thing\n");
fclose($fp);

You might also like