(M5-M7) PHP
(M5-M7) PHP
(M5-M7) PHP
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
Records (Row)
mysql > \s
Basic Commands
Basic Commands
• Need help?:
mysql > \h
mysql > ?
mysql > \?
* 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
• 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: PHPSetSession.php
Example: PHPUnsetSession.php
Session
Example: PHPDisplaySession.php
Example: PHPDeleteSession.php
Session
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
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
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
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[“MAX(tuition)”]
echo $fetch[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)”]
echo $fetch[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:
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);