My SQLPHP
My SQLPHP
20/5/13
3
WhatisisPHP
What PHP(Cont’d)
(cont’d)
Interpreted language, scripts are parsed at run-
time rather than compiled beforehand
Executed on the server-side
Source-code not visible by client
‘View Source’ in browsers does not display the PHP
code
Plethora of built-in functions allow for fast
development
Compatible with many popular databases
20/5/13
4
What does PHP code look like?
Structurally similar to C/C++
Supports procedural and object-oriented
paradigm (to some degree)
All PHP statements end with a semi-colon
Each PHP script must be enclosed in the
reserved PHP tag
<?php
…
?>
20/5/13
5
PHP Overview
•Easy learning curve
•Syntax Perl- and C-like syntax. Relatively easy to learn.
•Large function library
•Embedded directly into HTML
•Interpreted, no need to compile
•Open Source server-side scripting language designed
specifically for the web.
•Conceived in 1994, now used on +10 million web sites.
•Outputs not only HTML but can output XML, images (JPG &
PNG), PDF files and even Flash movies all generated on the fly.
Can write these files to the filesystem.
•Supports a wide-range of databases (20 + ODBC).
•PHP also has support for talking to other services using
protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP.
Comments in PHP
# Shell-style comments
/* C-style comments
These can span multiple lines */
20/5/13
7
Variables in PHP
20/5/13
8
Variable usage
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
20/5/13
9
Echo
20/5/13
10
Echo example
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with
25
Strings in single quotes (‘ ‘) are not interpreted or evaluated by PHP
This is true for both variables and character escape-sequences (such as
“\n” or “\\”)
20/5/13
11
PHP Control Structures
•Control Structures: Are the structures within a language that
allow us to control the flow of execution through a program or
script.
•Grouped into conditional (branching) structures (e.g. if/else) and
repetition structures (e.g. while loops).
•Example if/else if/else statement:
if ($foo == 0) {
echo ‘The variable foo is equal to 0’;
}
else if (($foo > 0) && ($foo <= 5)) {
echo ‘The variable foo is between 1 and 5’;
}
else {
echo ‘The variable foo is equal to ‘.$foo;
20/5/13 } 12
Functions
Functions MUST be defined before then can be
called
Function headers are of the format
function functionName($arg_1, $arg_2, …, $arg_n)
20/5/13
13
Functions example
<?php
// This is a function
function foo($arg_1, $arg_2)
{
$arg_2 = $arg_1 * $arg_2;
return $arg_2;
}
20/5/13
14
PHP - Forms
•Access to the HTTP POST and GET data is simple in PHP
•The global variables $_POST[] and $_GET[] contain the request
data
<?php
if ($_POST["submit"])
echo "<h2>You clicked Submit!</h2>";
else if ($_POST["cancel"])
echo "<h2>You clicked Cancel!</h2>";
?>
<form action="form.php" method="post">
20/5/13
16
WHY PHP – Sessions ?
Whenever you want to create a website that allows you to store and
display information about a user, determine which user groups a person
belongs to, utilize permissions on your website or you just want to do
something cool on your site, PHP's Sessions are vital to each of these
features.
Cookies are about 30% unreliable right now and it's getting worse every
day. More and more web browsers are starting to come with security and
privacy settings and people browsing the net these days are starting to
frown upon Cookies because they store information on their local
computer that they do not want stored there.
PHP has a great set of functions that can achieve the same results of
Cookies and more without storing information on the user's computer.
PHP Sessions store the information on the web server in a location that
you chose in special files. These files are connected to the user's web
browser via the server and a special ID called a "Session ID". This is
nearly 99% flawless in operation and it is virtually invisible to the user.
20/5/13
17
Destroy PHP - Sessions
Destroying a Session
why it is necessary to destroy a session when the session will get
destroyed when the user closes their browser. Well, imagine that you had
a session registered called "access_granted" and you were using that to
determine if the user was logged into your site based upon a username
and password. Anytime you have a login feature, to make the users feel
better, you should have a logout feature as well. That's where this cool
function called session_destroy() comes in handy. session_destroy() will
completely demolish your session (no, the computer won't blow up or self
destruct) but it just deletes the session files and clears any trace of that
session.
NOTE: If you are using the $_SESSION superglobal array like we are in
this tutorial, you must clear the array values first, then run
session_destroy.
Here's how we use session_destroy():
20/5/13
18
Saving Data in Text Files
PHP has built in functions for File I/O processing
fopen (..), fwrite(..), fclose(..), fflush(..),
file_get_contents(..)
Using these pre-made functions, File I/O in PHP
is similar to that of C
General Flow:
Open file
Read data
Modify data
Write data
Close file
20/5/13
19
Saving Data in Text Files
Reading from a file
<?php
$file = fopen("sample.txt", "r");
while (!feof($file)) {
echo fgets($file), "<BR>";
}
?>
Reading from a URL
<?php $file = fopen("http://www.php.net/file.txt", "r"); ?>
Writing to a file
<?php
$file = fopen("agent.log", "a");
fputs($file, $HTTP_USER_AGENT."\n");
?>
20/5/13
20
Saving Data in Text Files
Reading from a file
<?php
$file = fopen("sample.txt", "r");
while (!feof($file)) {
echo fgets($file), "<BR>";
}
?>
Reading from a URL
<?php $file = fopen("http://www.php.net/file.txt", "r"); ?>
Writing to a file
<?php
$file = fopen("agent.log", "a");
fputs($file, $HTTP_USER_AGENT."\n");
?>
20/5/13
21
Saving Data in Text Files
Reading a File directly into Array or String
The file() function reads entire file into an array: array file (string
filename [, int use_include_path]) Each element of the array
corresponds to a line in the file, with the newline still attached.
You can use the optional second parameter and set it to "1", if you
want to search for the file in the include_path, too.
20/5/13
22
Saving Data in Text Files: Example
<?php
$filename = 'test.txt'; /* Filename for writing. This is assumed to be in the same directory as
the script */
$somecontent = "Add this to the file\n"; // String to append to the file
20/5/13
23
PHP - Benefits
•Easy, powerful, popular
•Server-side scripting language
•Supports many DB’s (not only MySQL)
•Platform Independent
•Web Server Independent
•Free and Open Source
PHP Overtakes Microsoft ASP as the Web’s Number 1
server side Web technology for the Internet.
•An April Netcraft surveys indicate 24 percent of the
37.6 million websites, or are running PHP scripts. PHP
adoption is growing by 6.5 percent each month. (9
million sites)
20/5/13
24
Introduction to MySQL
MySQL Overview
20/5/13
26
MySQL – Database Basics
•A relational database manager (MySQL) manages databases
which holds tables which has records (rows) with attributes
(columns)
20/5/13
27
MySQL – Create Tables
Table structure for following examples:
CREATE TABLE oscarpool ( CREATE TABLE
uid int(4) auto_increment, bestdirector (
username varchar(255), bdid int(4)
email varchar(255), auto_increment,
bestpicture int(2), name varchar(255),
PRIMARY KEY (uid) PRIMARY KEY (bdid)
) )
Created two tables, ‘oscarpool’ & ‘bestdirector’ using:
(a) use MySQL either in line mode (cd c:\mysql\bin and mysql) or
(b) Use MySQL Control Center
(c) use phpMyAdmin tool
20/5/13
29
MySQL – SELECT
Common SQL Statement: SELECT
SELECT uid,username
FROM oscarpool
Selects the attributes ‘uid’ and ‘username’ from every
record in ‘oscarpool’
SELECT is how you query the database. You can also:
limit the number of records returned with LIMIT,
limit retrieval to those records that match a condition
with WHERE,
sort the data after the query has been evaluated using
ORDER BY
Tip: To easily select every attribute replace ‘uid’ with ‘*’
20/5/13
30
MySQL – UPDATE
Common SQL Statement: UPDATE
UPDATE oscarpool
SET email = ‘[email protected]’
WHERE uid = 1
20/5/13
31
MySQL – DELETE
Common SQL Statement: DELETE
20/5/13
32
MySQL – JOIN
SELECT bd.name
FROM oscarpool op, bestdirector bd
WHERE op.uid = 1 and
op.bestdirector = bd.bdid
20/5/13
33
MySQL – ERD
Entity-Relationship (ER) Modeling
ER Modeling is the simple and clear method of expressing the
design (relations) of a database between tables and attributes.
Rectangles – Represent entities.
Diamonds – Represent relationships
between entities
Ellipses – Represent attributes that
describe an entity
Lines – Connect entities to relationships.
Can have annotation.
M = many, 1 = one.
Lines – Connects entities to attributes. No annotation.
Entity = Table, Attributes = Attributes
20/5/13
34
MySQL – DB Access
<html>
<body>
<h1>A List of Users Who Have Signed Up For OscarPool</h1>
<?
$dbh = mysql_connect("localhost","root","")
or die("Couldn't connect to database.");
$db = mysql_select_db("test", $dbh)
or die("Couldn't select database.");
$sql = "SELECT username, email FROM oscarpool";
$result = mysql_query($sql, $dbh)
or die("Something is wrong with your SQL statement.");
Us
er
Apache - Benefits
•Apache is well supported - Most support for Apache is free and
available 24 hours a day via Internet mail or newsgroups.
•Apache is multi-platform - Apache can run on virtually any
hardware platform (from PCs to mainframes), and almost any operating
system, such as Linux, Windows, NetWare, Macintosh, xBSD, etc.
•Apache is secure - security holes are rare but when they exist they
are discovered and fixed quickly
•Apache is extensible - anyone can write modules that easily plug in
to Apache. If Apache doesn't do what you want or need it to do, anyone
with programming skills can write the modules you need.
•Apache is database-friendly - you can interface Apache with
virtually any commercial database, such as Oracle, Sybase, DB2, and
Informix, as well as free databases such as MySQL and Postgres.
•Apache is hardware-friendly - Apache generally consumes far fewer
hardware resources that commercial web servers.
•No Microsoft Viruses - Apache is immune to the Code Red, Nimda,
and other viruses that target at Microsoft Web servers.
20/5/13
44
Installation – Apache (ver 2.0.52)
•Go to http://httpd.apache.org/download.cgi
•Click Download
•Execute setup.exe
• Go to C:\mysql\bin
• Execute winmysqladmin.exe. You will be prompted for
username and password. Type as admin with password as
admin
•You will see the Traffic light signal on the task bar and
also the admin window
Configuration - MySQL
MySQL Control Center
•Graphical administrative interface for MySQL
database(s)
•Download from
http://dev.mysql.com/downloads/other/mysqlc
c.html
Establish connection
to DB server
20/5/13
53
MySQL Control Center - Configuration
in Databases ignore mysql; delete test
in User Administration delete
first two users and assign
password to root users
ignore Server Administration
adapt connection (password)
20/5/13
54
Installation - PHP
http://www.php.net/manual/en/
http://www.w3schools.com/php/default.asp
http://www.zend.com/zend/tut/
www.opensource.org
20/5/13
61
Sample Project with Codes
Sample Project
ONLINE
REGISTRATION
20/5/13
63
First Page
Here all the information regarding the user is entered and is updated
to the database on clicking the submit button. Validation is done by
checking whether the name and email fields are empty or not…
20/5/13
64
Invalid Information!
Validation Performed…
The user has to go back and fill up the necessary details…
20/5/13
65
User Registered
If all the information entered is valid, then the user is
registered.
i.e. the information is updated in the database.
20/5/13
66
Coding
test.html
<html>
<head>
<title> MyWebForm... </title>
</head>
<body bgcolor=brown>
<h1><font color=white>
Hello! This is ARIJIT CHOWDHURY...</h1>
<br><br>
<h2> Please fill up the following details in the form...</h2>
<br>
<h3> Please Note that the <font color=black>name</font> and <font color=black>emailID</font> are mandatory fields. i.e. they
must not be left empty...</h3>
</font>
<br>
<form action=submit.php method=post>
<table>
<tr>
<td><h3>Your Name:</h3></td>
<td><input type=text name="name"></td>
</tr>
67
Coding…
<tr>
<td><h3>Your email ID:</h3></td>
<td><input type=text name="mail"></td>
</tr>
<tr>
<td><h3>Your Mobile:</h3></td>
<td><input type=text name="mob"></td>
</tr>
<tr>
<td><h3>Your Age:</h3></td>
<td><input type=radio name=age value="Below 18"> Below 18</td>
<tr>
<td><input type=radio name=age value="18 to 25"> 18 to 25</td>
<td><input type=radio name=age value="25 to 40"> 25 to 40</td>
</tr>
<tr>
<td><input type=radio name=age value="40 to 60"> 40 to 60</td>
<td><input type=radio name=age value="Above 60"> Above 60</td>
</tr>
20/5/13
68
Coding…
<tr>
<td><h3>Your Sex:</h3></td>
</tr>
<tr>
<td><input type=radio name=sex value="male"> Male</td>
<td><input type=radio name=sex value="female"> Female</td>
</tr>
<tr>
<td><input type=reset></td>
<td><input type=submit value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
20/5/13
69
Coding…
submit.php
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
$name=$_POST['name'];
$mail=$_POST['mail'];
$mob=$_POST['mob'];
$age=$_POST['age'];
$sex=$_POST['sex'];
if ((empty($name))||(empty($mail)))
{
echo "<h1><font color=white>'Please fill up the mandatory fields(Name,EmailID)...'</font></h1>";
echo "<form action=test.html method=post><input type=submit value=GoBack></form>";
}
20/5/13
70
Coding…
else
{
if ($sex=="male")
echo "<h1><font color=white>Thank You, Sir!</font></h1>";
elseif ($sex=="female")
echo "<h1><font color=white>Thank You, Madame!</font></h1>";
else
echo "<h1><font color=white>Thank You!</font></h1>";
20/5/13
71
echo "<br><br><br><h1><font color=white>Thank You for Registering!<br> Your email ID $mail. Remember it for
logging in...</font></h1>";
}
?>
20/5/13
72
THANK YOU