Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 60

www.virtual-solutions.

in

PHP BASIC TUTORIAL

ARCHITECTURE

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 1


www.virtual-solutions.in

WAMP
WAMPs are packages of independently-created programs installed on computers
that use a Microsoft Windows operating system.

WAMP is an acronym formed from the initials of the operating system Microsoft
Windows and the principal components of the package:
Apache, MySQL and PHP (or Perl or Python, although WAMP includes PHP
exclusively). Apache is a web server. MySQL is an open-source database. PHP is a
scripting language that can manipulate information held in a database and generate

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 2


www.virtual-solutions.in

web pages dynamically each time content is requested by a browser. Other programs
may also be included in a package, such as phpMyAdmin which provides a graphical
user interface for the MySQL database manager, or the alternative scripting
languages Python or Perl.

WAMP is an integrated environment where we can use PHP, MySQL and Apache
webserver in Windows Operating System

Wamp Installation

Download latest version of WAMP from http://www.wampserver.com/en/.

The following screen schots are self-explanatory in the process of installing


the WAMP server in a Windows computer.

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 3


www.virtual-solutions.in

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 4


www.virtual-solutions.in

After installing you can load the WAMP server and on loading it, you can find the
WAMP tray in the taskbar at the right end. For the WAMP to work the Server has to
be put online and Start All The Services.

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 5


www.virtual-solutions.in

If everything is working fine, the below given screen or the index.php file should be
displayed when localhost// is entered in any browser.

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 6


www.virtual-solutions.in
The below given screenshots are self-explanatory for how to use phpmyadmin and to
create database, tables, enter values in a table and related stuffs.

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 7


www.virtual-solutions.in

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 8


www.virtual-solutions.in

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 9


www.virtual-solutions.in

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 10


www.virtual-solutions.in

Basics of PHP
Php Syntax

<?php
?>
(or)
<?
?>

Print statement

<?php
echo “PRINT STATEMENT”;
?>

Variables
There is no need to explicitly declare variables in php. The first value which
you assign to the variable will decide the variable datatype.
<?php
$txt="Hello World!";
$x=16;
echo $txt;

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 11


www.virtual-solutions.in
echo $x;
?>

The Concatenation Operator

 There is only one string operator in PHP.

 The concatenation operator (.) is used to put two string values


together.

<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>

The strlen() function

 The strlen() function is used to return the length of a string.

<?php
echo strlen("Hello world!");
?>

The strpos() function

 The strpos() function is used to search for character within a string.

 If a match is found, this function will return the position of the first
match. If no match is found, it will return FALSE.

<?php
echo strpos("Hello world!","world");
?>

Assignment Operators

Operator Example

= X=y

+= x+=y

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 12


www.virtual-solutions.in

-= X-=y

*= x*=y

/= x/=y

.= x.=y

%= x%=y

Comparison Operators

Operator Description Example

== is equal to 5==8 returns false

!= is not equal 5!=8 returns true

<> is not equal 5<>8 returns true

> is greater than 5>8 returns false

< is lesser than 5<8 returns true

>= is greater than or equal to 5>=8 returns false

<= is lesser than or equal to 5<=8 returns true

Logical Operators

Operator Description Example


x=6
&& and
y=3 (x < 10 && y > 1) returns true
x=6
|| or
y=3 (x==5 || y==5) returns false

x=6
! not
y=3 !(x==y) returns true

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 13


www.virtual-solutions.in

Control Statements

if statements

 if (condition) code to be executed if condition is true;

Sample code:
<?php
$d=Fri;
if ($d=="Fri") echo "Have a nice weekend!";
?>

if...else Statements

 if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Sample code:
<?php
$d=5;
$e=4;
If ($d==$e)
echo "Numbers are equal";
else
echo "Numbers are not equal";
?>

if...elseif....else Statements

 if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Sample code:
<?php
$d=Sun;
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 14


www.virtual-solutions.in
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>

Switch Statements

 switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}

Sample code:
<?php
switch (4)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>

Array

 A variable is a storage area holding a number or text. The problem is, a


variable will hold only one value.

 An array is a special variable, which can store multiple values in one


single variable.

 There are three kind of arrays

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 15


www.virtual-solutions.in

♦ Numeric array - An array with a numeric index


♦ Associative array - An array where each ID key is associated with
a value
♦ Multidimensional array - An array containing one or more arrays

Numeric Arrays

 There are two methods to create a numeric array.

o $cars=array("Saab","Volvo","BMW","Toyota");

o $cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";

Sample code:
<?php
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";
?>

Associative Arrays

 An associative array, each ID key is associated with a value.

 When storing data about specific named values, a numerical array is not
always the best way to do it.

 With associative arrays we can use the values as keys and assign values
to them.

 There are two methods to create a numeric array

o $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

o $ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";

Sample code:
<?php
$ages['Peter'] = "32";

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 16


www.virtual-solutions.in
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old.";
?>

Multidimensional Arrays

 In a multidimensional array, each element in the main array can also


be an array. And each element in the sub-array can be an array,
and so on.

Sample code:
<?php
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);
echo "Is " . $families['Griffin'][2] ." a part of the Griffin family?";
?>

PHP Looping

While Loops

while (condition)
{
code to be executed;
}

While Loop:

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 17


www.virtual-solutions.in
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
Do...while Statements

do
{
code to be executed;
}
while (condition);

Sample code:
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<=5);
?>

The for Loops

for (init; condition; increment)


{
code to be executed;
}

Sample code:
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>

The foreach Loop

foreach ($array as $value)


{

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 18


www.virtual-solutions.in
code to be executed;
}
Sample code:
<?php
$x=array("one","two","three");
foreach ($x as $value)
{
echo $value . "<br />";
}
?>

PHP Function

function functionName()
{
code to be executed;
}

Method 1 Sample code:

<?php
function writeName()
{
echo "Kai Jim Refsnes";
}

echo "My name is ";


writeName();
?>

Method 2 Sample code:

<?php
function writeName($fname)
{
echo $fname . " Refsnes.<br />";
}

echo "My name is ";


writeName("Kai Jim");
echo "My sister's name is ";
writeName("Hege");
echo "My brother's name is ";
writeName("Stale");
?>
Method 3 Sample code:

<?php
function writeName($fname,$punctuation)
{

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 19


www.virtual-solutions.in
echo $fname . " Refsnes" . $punctuation . "<br />";
}
echo "My name is ";
writeName("Kai Jim",".");
echo "My sister's name is ";
writeName("Hege","!");
echo "My brother's name is ";
writeName("Stale","?");
?>

Method 4 with Return Value Sample code:

<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>

HTML FORM

<html>
<body>
<form action="print.php" method="post">
Name: <input type="text" name="fname" /><br>
Age: <input type="text" name="age" /><br>
male
<label>
<input type="radio" name="radio" id="radio" value="radio" />
female
<input type="radio" name="radio2" id="radio1" value="radio1" />
</label>
<input type="submit" /><br>
</form>
</body>
</html>
PHP Methods

Two types to pass the value from html to php are

 GET method

 POST method

GET METHOD:

$a=$_GET[‘name’];

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 20


www.virtual-solutions.in
where name is value from the user in get method.

POST METHOD:

$a=$_POST[‘name’];

where name is value from the user in post method.

DIFFERENCE BETWEEN GET AND POST

 When using GET method the values which are passed can be seen in
address bar.

 But these values cannot be seen in address bar in POST method.

Basics of HTML FORMS

HTML FORM TEXT BOX

<html>
<body>

<form action="print.php" method="post">


Name: <input type="text" name="fname" /><br>
Age: <input type="text" name="age" /><br>
<input type="submit" /><br>
</form>

</body>
</html>

welcome.php

<?php
echo $_POST["fname"];
echo $_POST["age"];
?>

Form output:

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 21


www.virtual-solutions.in

MENU/LIST

 The <select> tag is used to create a select list (drop-down list).

 The <option> tags inside the select element define the available options
in the list.

Sample Code

<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Output:

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 22


www.virtual-solutions.in

Menu
Sample Code

<select multiple name="music" size="4">


<option value="emo" selected>Emo</option>
<option value="metal/rock" >Metal/Rock</option>
<option value="hiphop" >Hip Hop</option>
<option value="ska" >Ska</option>
<option value="jazz" >Jazz</option>
<option value="country" >Country</option>
<option value="classical" >Classical</option>
<option value="alternative" >Alternative</option>
<option value="oldies" >Oldies</option>
<option value="techno" >Techno</option>
</select>
Output

Radio

 <input type="radio" />

 defines a radio button. Radio buttons let a user select ONLY ONE one of a
limited number of choices

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 23


www.virtual-solutions.in
Sample Code
<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>

Output

Option

<option> tag

Sample Code
<select>
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</select>
Output

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 24


www.virtual-solutions.in

Comments

 The <textarea> tag defines a multi-line text input control.

Sample Code

<textarea rows="2" cols="20">


At W3Schools you will find all the Web-building tutorials you need, from basic HTML
to advanced XML, SQL, ASP, and PHP.
</textarea>

Output

Pictures
 Can Upload Images using multipart/form-data

Sample Code:

<form enctype="multipart/form-data" method="post">


<input type="file" name="datafile" size="40">
</form>

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 25


www.virtual-solutions.in

Output

Check Box

 A small box on which an x or check mark appears when the option.


 <input type="checkbox" /> defines a checkbox. Checkboxes let a user select
ONE or MORE options of a limited number of choices.

Sample Code
<form>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br/>

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 26


www.virtual-solutions.in
<input type="checkbox" name="vehicle" value="Car" /> I have a car
</form>

Output

HTML FORM EXAMPLE:

<form action="post.php" method="post" name="form">


<p>Name
<input type="text" name="name" id="name" />
<br />
<input type="radio" name="sex" value="male" />
Male<br />
<input type="radio" name="sex" value="female" />
Female<br/>
<input type="checkbox" name="vehicle" value="Bike" />
I have a bike<br/>
<input type="checkbox" name="vehicle" value="Car" />
I have a car <br/>
<select name="car">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select> <br />
<label>
<textarea name="area" id="area" cols="45" rows="5"></textarea>
</label><br />

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 27


www.virtual-solutions.in
<input type="submit" />
</form>

Post.php

<?php
$name=$_POST['name'];
$sex=$_POST['sex'];
$check=$_POST['vehicle'];
$select=$_POST['car'];
$area=$_POST['area'];

echo $name."<br>";
echo $sex."<br>";
$N = count($check);
for($i=0; $i < $N; $i++)
{
echo($check[$i] . " ")."<br>";
}
echo $select."<br>";
echo $area."<br>";
?>
Output

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 28


www.virtual-solutions.in

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 29


www.virtual-solutions.in

PHP Date()

 d - Represents the day of the month (01 to 31).

 m - Represents a month (01 to 12).

 Y - Represents a year (in four digits).

Sample code:
<?php
echo date("Y/m/d") . "<br />";
echo date("Y.m.d") . "<br />";
echo date("Y-m-d")."<br/>";
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "Tomorrow is ".date("Y/m/d", $tomorrow);
?>

Output:

PHP include() Function

 The include() function takes all the content in a specified file and includes
it in the current file.
 If an error occurs, the include() function generates a warning, but the
script will continue execution.

Homepage.php

<html>
<body>

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 30


www.virtual-solutions.in
<?php
include("header.php");
?>
<h1>Welcome to my homepage</h1>
<p>Some text.</p>
</body>
</html>

header.php:

<html>
<body>
<h1>HOME PAGE</h1>
<p>Some text.</p>
</body>
</html>
Output:

File Handling
Opening a File

 The fopen() function is used to open files in PHP.

Sample code:
<html>
<body>

<?php
$file=fopen("welcome.txt","r");
?>

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 31


www.virtual-solutions.in
</body>
</html>

Modes Description

r Read only. Starts at the beginning of the file

r+ Read/Write. Starts at the beginning of the file


Write only. Opens and clears the contents of file; or
w
creates a new file if it doesn't exist
Read/Write. Opens and clears the contents of file; or
w+
creates a new file if it doesn't exist
Append. Opens and writes to the end of the file or
a
creates a new file if it doesn't exist
Read/Append. Preserves file content by writing to the
a+
end of the file
Write only. Creates a new file. Returns FALSE and an
x
error if file already exists
Read/Write. Creates a new file. Returns FALSE and an
x+
error if file already exists

Closing a File

<?php
$file = fopen("test.txt","r");

//some code to be executed

fclose($file);
?>

Check End-of-file

if (feof($file)) echo "End of file";

Reading a File Line by Line

<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{ echo fgets($file). "<br />"; }
fclose($file);
?>

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 32


www.virtual-solutions.in
Reading a File Character by Character

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>

Write

Syntax: $myFile = "testFile.txt"; $fh = fopen($myFile, 'w');

Sample code:
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);
?>

Upload-File Form

<html>
<body>

<form action="upload_file.php" method="post"


enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

upload_file.php

<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 33


www.virtual-solutions.in
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>

Upload output:

Upload output:

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 34


www.virtual-solutions.in

Cookies
A cookie is often used to identify a user. A cookie is a small file that the server
embeds on the user's computer. Each time the same computer requests a page with

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 35


www.virtual-solutions.in
a browser, it will send the cookie too. With PHP, you can both create and retrieve
cookie values.

Sample code:
<?php
setcookie("user", "Alex Porter", time()+3600);
?>

How to Retrieve a Cookie Value?

<?php
// Print a cookie
echo $_COOKIE["user"];

// A way to view all cookies


print_r($_COOKIE);
?>

How to Delete a Cookie?

<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>

Sessions
A PHP session variable is used to store information about, or change settings for a
user session. Session variables hold information about one single user, and are
available to all pages in one application.

Session syntax: <?php


session_start();
?>

Sample code:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>

<html>
<body>

<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 36


www.virtual-solutions.in

</body>
</html>

A Basic E mail Sending


<?php
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>

Database Programming using PHP


PHP DATABASE mysql

 MySQL is a database.

 The data in MySQL is stored in database objects called tables.

 A table is a collection of related data entries and it consists of columns


and rows.

Connection to a MySQL Database:

Syntax: mysql_connect(servername,username,password);

Opening connection:

<?php
$con = mysql_connect("localhost",“root",“root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 37


www.virtual-solutions.in
// some code
?>

Closing connection:

<?php
$con = mysql_connect("localhost",“root",“root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// some code

mysql_close($con);
?>

Create a Database:

Syntax: CREATE DATABASE database_name

Sample code:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

if (mysql_query("CREATE DATABASE my_db",$con))


{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}

mysql_close($con);
?>

Create a Database output:

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 38


www.virtual-solutions.in

Create a Table

Syntax: CREATE TABLE table_name


(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)

Sample code:

$con = mysql_connect("localhost","root","");
<?php
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_dbq",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_select_db("my_dbq", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 39


www.virtual-solutions.in
)";
echo "TABLES CREATED";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>

Table output:

Insert Data Into a Database Table

INSERT INTO table_name


VALUES (value1, value2, value3,...)

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

Sample code:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)


VALUES ('Peter', 'Griffin', '35')");

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)


VALUES ('Glenn', 'Quagmire', '33')");

echo "values inserted";

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 40


www.virtual-solutions.in

mysql_close($con);
?>

Output:

Insert Data From a Form Into a Database

<html>
<body>

<form action="insert.php" method="post"><br>


Firstname: <input type="text" name="firstname" /><br>
Lastname: <input type="text" name="lastname" /><br>
Age: <input type="text" name="age" /><br>
<input type="submit" />
</form>

</body>
</html>

Insert from user

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$sql="INSERT INTO Persons (FirstName, LastName, Age)VALUES


('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 41


www.virtual-solutions.in
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>

Insert from user output:

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 42


www.virtual-solutions.in

Select Data From a Database Table

Syntax: SELECT column_name(s)


FROM table_name

Sample code:

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons");

while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}

mysql_close($con);
?>

Select Data output:

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 43


www.virtual-solutions.in

The WHERE clause

Syntax: SELECT column_name(s)


FROM table_name
WHERE column_name operator value

Sample code:

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons WHERE FirstName='Peter'");

while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?>

WHERE clause output:

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 44


www.virtual-solutions.in

Update Data In a Database

Syntax: UPDATE table_name


SET column1=value, column2=value2,...
WHERE some_column=some_value

Sample code:

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

mysql_query("UPDATE Persons SET Age = '36‘ WHERE FirstName = 'Peter'


AND LastName = 'Griffin'");

echo "VALUES UPDATED";

mysql_close($con);
?>

Update output:

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 45


www.virtual-solutions.in

Delete Data In a Database

Syntax: DELETE FROM table_name WHERE


some_column = some_value

Sample code:

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

mysql_query("DELETE FROM Persons WHERE LastName='Griffin'");

echo "DATAS DELETED";

mysql_close($con);
?>

Output:

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 46


www.virtual-solutions.in

User Authentication in PHP

 Here are some authentication method that we'll discuss

 Basic authentication
We hard code the username and password combination in the login script
itself. Suitable for simple application

 User & password stored in database


A very common method. We store all the user name and password
information in the database

 User authentication with image verification


This is a more advance method of user authentication. We can prevent
any automatic login by a robot ( script ) by using this method

User Authentication

<?php
if (function_exists('imagecreate')) {
echo "GD Library is enabled <br>\r\n<pre>";
var_dump(gd_info());
echo "</pre>"; }
else {
echo 'Sorry, you need to enable GD library first'; }
?>
Output:

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 47


www.virtual-solutions.in

Basic javascript

What is JavaScript?

 JavaScript was designed to add interactivity to HTML pages

 JavaScript is a scripting language

 A scripting language is a lightweight programming language

 JavaScript is usually embedded directly into HTML pages

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 48


www.virtual-solutions.in

 JavaScript is an interpreted language (means that scripts execute


without preliminary compilation)

 Everyone can use JavaScript without purchasing a license

Basic javascript:

<html>
<body>

<script type="text/javascript">
document.write("This is my first JavaScript!");
</script>

</body>
</html>

Sample code:

<head><script type="text/javascript">
function valid()

var a=document.getElementById("login");
var b=document.getElementById("password");
if(a.value=="" || b.value=="")
{
alert ("Fields are empty");
}
</script>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td colspan="2" bgcolor="#FFFFFF"><img src="Logo.gif" alt=""
width="171" height="75"></td>
</tr>
</table>
<table width="100%" bgcolor="#00AEEF">
<tr>
<td ></td>
</tr>
</table>
<form action="login.php" method="post"
name="formlogin“onSubmit="javascript:return valid()" >
<p align="center">&nbsp;</p>
<p align="center" style=" margin-left:10px">
<span class="style3">Login ID</span>
<input type="text" name="login" id=“login”/>
</p>
<p align="center">
<span class="style3">Password</span>

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 49


www.virtual-solutions.in
<input type="password" name="password“ id=“password” />
</p>
<p align="center">
<input name="Login" type="submit" id="Login" value="Login"
style="margin-left:60px" />
</p>
<p align="center">&nbsp;</p>
<p align="center">&nbsp;</p>
<p align="center">&nbsp;</p>
<p align="center">&nbsp;</p>
<p align="center ">&nbsp;</p>
</form>
Output:

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 50


www.virtual-solutions.in

CSS
 CSS stands for Cascading Style Sheets.

 Styles define how to display HTML elements.

Syntax:

Id and Class

 The id Selector
#para1
{
text-align:center;
color:red;
}

 Class selector
center {text-align:center;}

Three Ways to Insert CSS

 External style sheet

 Internal style sheet

 Inline style

External Style Sheet

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
</head>

Internal Style Sheet

<head>
<style type="text/css">
hr {color:sienna;}
p {margin-left:20px;}

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 51


www.virtual-solutions.in
body {background-image:url("images/back40.gif");}
</style>
</head>

Inline Styles

<p style="color:sienna;margin-left:20px">This is a paragraph.</p>

Css properties

Styling Backgrounds

• background-color

• background-image

• background-repeat

• background-attachment

• background-position

Text formatting

• color

• text-align

• text-decoration

• text-transform

• text-indent

Font

• font-family

• font-style

• font-size

Links

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 52


www.virtual-solutions.in

• a:link {color:#FF0000;} /* unvisited link

• a:visited {color:#00FF00;} /* visited link

• a:hover {color:#FF00FF;} /* mouse over link

• a:active {color:#0000FF;} /* selected link

List

• ul.a {list-style-type: circle;}

• ul.b {list-style-type: square;}

• ol.c {list-style-type: upper-roman;}

• ol.d {list-style-type: lower-alpha;}

Where ul is unordered list and ol is ordered list.

Padding

• padding-top;

• padding-bottom;

• padding-right;

• padding-left;

padding-top:25px;
padding-bottom:25px;
padding-right:50px;
padding-left:50px;

Can be written as

Padding: 25px 25px 50px 50px;

Grouping Selectors

h1
{
color:green;
}
h2
{

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 53


www.virtual-solutions.in
color:green;
}
p
{
color:green;
}

Can be written as

h1,h2,p
{
color:green;
}

Examples of Css link:

Head Section:

<head>
<link href="css/stylesheet.css" rel="stylesheet" type="text/css" />
</head>

Body Section

<p class="font" align="justify">Children are the living messages we


send to a time we will not see. India, by one count, has 18 million
street children and over 22 million child laborers.</p>

<p class=“font1” align=“justify”> Millions of children go to bed each


night, hungry and without the warmth of a home. Many have neither
been to school nor have access to basic healthcare.</p>

stylesheet.css

.font{
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:11px;
}
.font1{
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:11px;
Color:#2887E1;
}

PHP EDITORS
Dreamweaver
PHP designer

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 54


www.virtual-solutions.in
Notepad

OPEN SOURCE
Open-source software (OSS) is computer software that is available in source code
form for which the source code and certain other rights normally reserved for
copyright holders are provided under a software license that permits users to study,
change, and improve the software.

PHP OPEN SOURCE CATEGORIES:

1. Content Management System(CMS)


2. Learning Management System (LMS)
3. Social Networking
4. Ecommerce
5. Client Relationship Management(CRM)
6. Blog

Content Management System


1. Drupal
2. Joomla

Learning Management System


1. Moodle

Social Networking
1. Elgg
2. Mahara

Ecommerce
1. Oscommerce
2. Magento
3. Zencart

Client Relationship Management


1. Vtiger
2. Sugar CRM

Blog
1. Wordpress

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 55


www.virtual-solutions.in

OOPS CONCEPT IN PHP

OOP language should have:

 Abstract data types and information hiding


 Inheritance
 Polymorphism

<?php

class Something {
// In OOP classes are usually named starting with a cap letter.
var $x;

function setX($v) {
// Methods start in lowercase then use lowercase to separate
// words in the method name example getValueOfArea()
$this->x=$v;
}

function getX() {
return $this->x;
}
}

?>

CLASSES

 A class is technically defined as a representation of an abstract


data type. In laymen's terms a class is a blueprint from which new
will construct our box. It's made up of variables and functions
that allow our box to be self-aware.

Sample Code

<?php
class Box
{
var $contents;

function Box($contents) {
$this-&gt;contents = $contents;
}

function get_whats_inside() {
return $this-&gt;contents;
}

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 56


www.virtual-solutions.in
}

$mybox = new Box("Jack");


echo $mybox-&gt;get_whats_inside();
?>

Methods

 To ask the box what it contains, the special get_whats_inside function was
used. Functions defined in the class are known as methods; they act as a
method for communicating with and manipulating the data within the box.
 The nice thing about methods is that they allow us to separate all the class
coding from our actual script.
 We could save all of the class code in a separate file and then use include to
import it into our script. Our scripts become more streamlined and, because
we used descriptive names for our methods, anyone else reading our code
can easily see our train-of-thought.

Sample Code

<?php
include("class.Box.php");

$mybox = new Box("Jack");


echo $mybox-&gt;get_whats_inside();

?&gt;
?>

Extends

We could add more methods to our class, but what if we were building
extensions to someone else's class? We don't have to create an entirely
new class to add new functionality. we can build a small extension class
based on the original.

Sample Code

<?php
;
include("class.Box.php");

class ShoeBox extends Box


{
varr $size;

function ShoeBox($contents, $size) {


$this-&gt;contents = $contents;
$this-&gt;size = $size;
}

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 57


www.virtual-solutions.in

function get_shoe_size() {
return $this-&gt;size;
}
}

$mybox = new ShoeBox("Shoes", 10);


echo $mybox-&gt;get_whats_inside();
echo $mybox-&gt;get_shoe_size();
?>

The ability to write such modular additions to your code gives great
flexibility in testing out new methods and saves time by reusing the
same core code.

<?php
include("class.Box.php");
include("extentions.Shoe.php");
include("extentions.Suggestion.php");
include("extentions.Cardboard.php");

$mybox = new ShoeBox("Shoes", 10);


$mySuggestion = new SuggestionBox("Complaints");
$myCardboard = new CardboardBox('', "corrugated", "18in", "12in", "1
0in");
?>

Constructor

Developers can declare constructor methods for classes. In this, those classes which
have a constructor method call this method for each newly created object. So, it
is suitable for any initialization that the object may need before it is used. In this
the parent constructors are not called implicitly if the child class defines a
constructor.

Example

<?php
class ParentClass {

function __construct() {

print "In ParentClass constructor\n";

class ChildClass extends ParentClass {

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 58


www.virtual-solutions.in
function __construct() {

parent::__construct();

print "In ChildClass constructor\n";

$obj = new ParentClass();

$obj = new ChildClass();

?>

Destructors

 This destructor concept is similar to other object oriented languages. In this


the destructor will be called as soon as all references to a particular object
have been removed or when the object has been explicitly destroyed.

Example

<?php

class MyClass {

function __construct() {

print "In constructor\n";

$this->name = "MyClass";

function __destruct() {

print "Destroying " . $this->name . "\n";

$obj = new MyClass();

?>

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 59


www.virtual-solutions.in

Patterns

 Patterns are ways to describe best practices and good designs. The patterns
show a flexible solution to common programming problems.

Example

<?php

class Welcome

// The parameterized factory method

public static function factory($type)

if (include_once 'Drivers/' . $type . '.php') {

$classname = 'Driver_' . $type;

return new $classname;

} else {

throw new Exception ('Driver not found');

?>

Dr.M.G.R.University – PHP/MySQL Training September 13-18 2010 60

You might also like