wt-unit4-php
wt-unit4-php
WT unit4 - PHP
WebTechnologies
UNIT –IV
PHP Programming: Introducing PHP: Creating PHP script, Running PHP script.
Working with variables and constants: Using variables, Using constants, Data types,
Operators. Controlling program flow: Conditional statements, Control statements,
Arrays, functions. Working with forms and Databases such as mySql, Oracle, SQL
Server.
Introduction to PHP:
Apache 1
2 Web Page
PHP Internet On
script Browser
3 5 6
PHP
4
MySql
DataBase MiddleWare
WebTechnologies
Installing PHP:
Download PHP
WebTechnologies
A PHP script always starts with <?php and ends with ?>.
A PHP script can be placed anywhere in the document
A PHP file must have a .php extension.
A PHP file normally contains HTML tags, and some PHP scripting code.
Example:
<html>
<body bgcolor="pink">
<center> <font size=15 color="blue">
<?Php
echo "WELCOME TO PHP WORLD";
?>
</font></center>
</body>
</html>
Comments in PHP:
Example:
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
WebTechnologies
*/
?>
</body>
</html>
KeyWords:
Variables
Variables are used for storing values, like text strings, numbers or arrays.
PHP makes use of dynamic typing that means there is no need to declare the variables.
When a variable is declared, it can be used over and over again in the script.
All variables in PHP start with a $ sign symbol.
If the value cannot assign to the variable, then by default the value is NULL. The unsigned
values are called as unbounded variables.
If the unbound variable is used in the expression, then its NULL value is converted to 0.
Rules for PHP variable names:
o Variables in PHP starts with a $ sign, followed by the name of the variable
WebTechnologies
o The variable name must begin with a letter or the underscore character
o A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
o A variable name should not contain spaces
o Variable names are case sensitive (y and Y are two different variables)
Example:
<?php
$str="Nalini durga";
?>
<html>
<body bgcolor="pink">
<center>
<font size=5><i>WELCOME TO PHP WORLD</i></font><br><br>
<?php
echo "Welcome" ." ".$str;
?>
</center>
</body>
</html>
Example:
<?php
$a=10;
$b=20;
$c=$a+$b;
?>
<html>
<body bgcolor="pink">
<center>
<font size=5><i>WELCOME TO PHP WORLD</i><br><br>
<?php
echo "Addtion of two numbers $a & $b is:" . " ". $c;
?>
</font>
</center>
</body>
WebTechnologies
</html>
Constants
Example:
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Differences between constants and variables are:
o There is no need to write a dollar sign ($) before a constant, where as in Variable one
has to write a dollar sign.
o Constants cannot be defined by simple assignment, they may only be defined using the
define() function.
o Constants may be defined and accessed anywhere without regard to variable scoping
rules.
o Once the Constants have been set, may not be redefined or undefined.
DataTypes:
Integer Type:
WebTechnologies
It is not compulsory to have digits before and after the decimal point.
Boolean Type:
There are only two values that can be defined by Boolean type.
Those are false and true.
String Type:
Arithmetic Operators
/ Division 15/5 3
5/2 2.5
% Modulus (division remainder) 5%2 1
10%8 2
10%2 0
WebTechnologies
Assignment Operators:
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
%= x%=y x=x%y
Relational Operators:
WebTechnologies
Logical Operators:
String Operator:
Concatnation is only the operartor used in string
(.) operator is used as concatenation operator
Example:
<html>
<body bgcolor="pink">
<center>
<font size=5><i>WELCOME TO PHP </i><br><br>
<?php
$txt1="Hello !";
$txt2=" NaliniDurga !";
echo $txt1 . " " . $txt2;
?>
</font>
</center>
</body>
WebTechnologies
</html>
Conditional Operator:
There is one more operator called conditional operator. This first evaluates an expression
for a true or false value and then execute one of the two given statements depending upon
the result of the evaluation. The conditional operator has this syntax:
Functions in Strings:
strlen() : The strlen() function is used to return the length of a string.
Example:
<?php
echo strlen("Hello world!");
?>
Output: 12
strpos() :
o The strpos() function is used to search for a character/text within a string.
o If a match is found, this function will return the character position of the first match.
If no match is found, it will return FALSE.
Example:
<?php
echo strpos("Hello world!","world");
?>
Output: 6
WebTechnologies
Strcmp(str1,str2):
<?php
echo strcmp("world","world");
?>
Output: 0
Example:
<?php
echo strtolower("HELLO!");
?>
Example:
<?php
echo strtoupper("Hello world ");
?>
trim(string): This function eliminates the white space from both ends of the string.’
Example:
<?php
$str= ” PHP “;
echo “<h3>:$str</h3>”;
echo “<h3>:trim($str)</h3>”;
WebTechnologies
?>
Conditional Statements
if statement :
if (condition)
{
code to be executed if condition is true;
}
Example:
<html>
<body bgcolor="pink">
<center><font size=15>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Have a nice weekend!";
}
else
{
echo "Hi Friends.......";
}
?>
</font>
WebTechnologies
</center>
</body>
</html>
if...else statement :
Syntax:
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
switch statement:
syntax:
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;
}
Example:
<html>
<body>
<?php
$x=1;
switch ($x)
WebTechnologies
{
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";
}
?>
</body>
</html>
Control Statements
while Statement: The while loop executes a block of code while a condition is true.
Syntax:
while (condition)
{
code to be executed;
}
Example:
<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
WebTechnologies
</body>
</html>
do...while Statement:
The do...while statement will always execute the block of code once, it will then
check the condition, and repeat the loop while the condition is true.
Syntax:
do
{
code to be executed;
}
while (condition);
Example:
<html>
<body bgcolor="pink">
<center>
<font color="green" size=5>
<?php
$i=1;
do
{
$i++;
echo "$i * $i = " . $i *$i. "<br />";
}
while ($i<10);
?>
</font>
</center>
</body>
</html>
WebTechnologies
Syntax:
Example:
<html>
<body>
<?php
for ($i=1; $i<=2; $i++)
{
for($j=1; $j<=10; $j++)
echo "$i * $j = " . $i*$j ."</br>";
}
?>
</body>
</html>
Syntax:
Example:
<html>
<body bgcolor="pink">
<center>
<font color="green" size=5><p>Displying the array content using foreach loop</p>
<?php
$x=array("one","two","three");
foreach ($x as $value)
WebTechnologies
{
echo $value . "<br />";
}
?>
</font>
</center>
</body>
</html>
Arrays
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.
An array stores multiple values in one single variable.
In PHP, there are three kind of arrays:
Numeric array:
Syntax: $array_name=array(10,20,30);
Example:
$cars=array("Saab","Volvo","BMW","Toyota");
Syntax: $array_name[]=value;
Example:
WebTechnologies
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
Syntax: $array_name=array();
Associative array
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.
Syntax:
$array_name=array(“key”=>”value”, “key”=>”value”);
Example:
Functions
To keep the script from being executed when the page loads, we must put it into function.
Syntax:
WebTechnologies
function functionName()
{
code to be executed;
}
Example:
<html>
<body bgcolor="pink">
<font size=10>
<center>
<?php
function sample()
{
echo "Welcome To PHP Home Page";
}
Example:
<html>
<body bgcolor="pink">
<font size=7>
<center>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "sum of 2 & 3 is: " . add(2,3);
?>
</font></center>
WebTechnologies
</body>
</html>
Returning value from the Function:
The PHP $_GET and $_POST variables are used to retrieve information from forms, like
user input.
$_GET : The predefined $_GET variable is used to collect values in a form with
method="get"
$_POST : In PHP, the predefined $_POST variable is used to collect values in a form
with method="post".
Example:
<html>
<body bgcolor="pink">
<center>
<u><p>Register Here</p></u><br>
<form name="form1" action="display.php" method="GET">
<table border=0>
<tr>
<td>Id</td>
<td><input type="text" name="Id"></td>
</tr>
<tr>
<td>Firstname</td>
<td><input type="text" name="FirstName"></td>
</tr>
<tr>
<td>LastName</td>
<td><input type="text" name="LastName"></td>
WebTechnologies
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="Age"></td>
</tr>
</table></br>
<input type="submit" value="submit">
</center>
</form>
</body>
</html>
<?php
echo "<center>";
echo "<table border='2'>
<tr>
<th>Id</th>
<th>FirstName</th>
<th>LastName</th>
<th>Age</th>
</tr>";
echo "<tr>";
echo "<td>" . $_GET['Id'] . "</td>";
echo "<td>" . $_GET['FirstName'] . "</td>";
echo "<td>" . $_GET['LastName'] . "</td>";
echo "<td>" . $_GET['Age'] . "</td>";
echo "</tr>";
echo "</table>";
echo "</center>";
?>
Example 2:
<html>
WebTechnologies
<body bgcolor="pink">
<center>
<font color="green" size=5>
<form action="switch1.php" method="POST">
Enter ur Choice <input type="text" name="num"><br><br>
<input type="submit" value="click me">
</form>
<?php
if($x=$_POST['num'])
{
echo "The number u entered is:".$x;
}
else
{
echo "welcome" ;
}
?>
</font>
</center>
</body>
</html>
MySql:
WebTechnologies
o Before accessing the data in a database, we must create a connection to the database.
Syntax:
mysql_connect(“servername”,”username”,”password”);
Example:
<?php
$con = mysqli_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
else
{
echo "connected.........";
}
?>
Syntax:
Example:
WebTechnologies
<?php
mysqli_close($con);
?>
Creating Data Base Tables:
<?php
//connection to server
$con = mysqli_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
else
{
WebTechnologies
echo "connected.........";
}
//database selection
if(mysqli_select_db($con,"rama"))
{
echo "selected";
}
else
{
echo " not selected";
}
// Execute query
if(mysqli_query($con,$sql))
{
echo "table created";
}
else
{
echo "not created";
}
mysqli_close($con);
The INSERT INTO statement is used to add new records to a database table.
It is possible to write the INSERT INTO statement in two forms.
WebTechnologies
<?php
//connection to server
$con = mysqli_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
else
{
echo "connected.........";
}
//database selection
if(mysqli_select_db($con,"rama"))
{
echo "selected";
}
else
{
echo " not selected";
}
// Execute query
if(mysqli_query($con,$query))
{
echo "data inserted";
}
WebTechnologies
else
{
echo "not inserted";
}
//Closing Connection
mysqli_close($con);
?>
Syntax:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Example:
<?php
//connection to server
$con = mysqli_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
else
{
echo "connected.........";
WebTechnologies
//database selection
mysqli_select_db( $con,"rama");
if(mysqli_query($con,$query))
{
echo "successfully updated";
}
else
{
echo "not updated";
}
//Closing Connection
mysqli_close($con);
?>
Deleting Data from table:
The DELETE FROM statement is used to delete records from a database table.
Example:
<?php
//connection to server
$con = mysqli_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
else
{
WebTechnologies
echo "connected.........";
}
//database selection
mysqli_select_db( $con,"rama");
//deleting data
mysqli_close($con);
?>
Inserting the Data From Registration Form into database:
Reg.html:
<html>
<body bgcolor="pink">
<center>
<u><p>Register Here</p></u><br>
<form name="form1" action="insert.php" method="POST">
<table border=0>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Email id</td>
<td><input type="text" name="email"></td>
</tr>
WebTechnologies
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>Contact No</td>
<td><input type="text" name="contact"></td>
</tr>
</table></br>
<input type="submit" value="submit">
</center>
</form>
</body>
</html>
Whenever we enter the details and click on the submit button, the control goes to
insert.php
insert.php:
<html>
<body bgcolor="pink">
<?php
//connection to server
$con = mysqli_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
//database selection
mysqli_select_db($con,"rama");
WebTechnologies
// Execute query
if(mysqli_query($con,$sql))
{
echo "table created";
}
if(mysqli_query($con,$sql))
{
echo"Suceessfully Registered";
}
else
{
echo"Sorry! Registration Failed";
echo"Try again";
}
//Closing Connection
mysqli_close($con);
?>
</body>
</html>
WebTechnologies
<html>
<body bgcolor="pink">
<?php
//Connecting to Server
$con = mysqli_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
//database selection
mysqli_select_db($con,"rama");
//Selecting data
$query="select * from student";
//Executing query
$result = mysqli_query($con,$query);
//Table Format
echo "<table border='2' align='center'>
<tr>
<th>Name</th>
<th>Email Id</th>
<th>Password</th>
<th>Contact No</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Emailid'] . "</td>";
echo "<td>" . $row['Password'] . "</td>";
echo "<td>" . $row['ContactNo'] . "</td>";
echo "</tr>";
}
echo "</table>";
//Closing Connection
mysqli_close($con);
?>
</body>
WebTechnologies
</html>
login.html:
<html>
<body bgcolor="pink">
<form action="validate.php" method="POST">
<table border=0 align='center'>
<tr>
<td>Id</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd"></td>
</tr>
<tr><td></td><td align='center'><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
validate.php:
<html>
WebTechnologies
<body bgcolor="pink">
<?php
$id=$_POST['email'];
$password=$_POST['pwd'];
//Connecting to Server
$con = mysqli_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
//database selection
mysqli_select_db($con,"rama");
//Selecting data
$query="select * from student";
//Executing query
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
if($id==$row['Emailid'] && $password==$row['Password'])
{
echo" authenticated User:";
}
}
//Closing Connection
mysqli_close($con);
?>
</body>
</html>
WebTechnologies
It is possible to insert the content of one PHP file into another PHP file (before the
server executes it), with the include or require statement.
The include and require statements are identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will
continue
include 'filename';
or
require 'filename';
Example Footer.php
<?php
echo "<p>Copyright © 1999-" . date("Y") . " W3Schools.com</p>";
?>
PHP
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>
</body>
</html>
Use include when the file is not required and application should continue when file
is not found.
Use :
WebTechnologies
Require:
Warning Error
A warning error in PHP does not stop the script from running. It only warns you
that there is a problem, one that is likely to cause bigger issues in the future.
For instance:
<?php
include ("external_file.php");
WebTechnologies
?>
Notice Error
Notice errors are minor errors. They are similar to warning errors, as they also
don’t stop code execution. Often, the system is uncertain whether it’s an actual
error or regular code. Notice errors usually occur if the script needs access to an
undefined variable.
Example:
<?php
$a="Defined error";
echo $b;
?>
WebTechnologies
Parse Error
Parse errors are caused by misused or missing symbols in a syntax. The
compiler catches the error and terminates the script.
For example, the following script would stop execution and signal a parse error:
<?php
echo "Red";
echo "Blue";
echo "Green"
?>
Fatal Error
Fatal errors are ones that crash your program and are classified as critical
errors. An undefined function or class in the script is the main reason for this
type of error.
WebTechnologies
3. Runtime fatal error (happens while the program is running, causing the code
to stop working completely)
<?php
function sub()
$sub=6-1;
div();
?>
The output tells you why it is unable to compile, as in the image below:
XAMPP
It has more extensions compared to WAMP.
WebTechnologies
XAMPP is known for its clean, simple interface; ideal for beginners.
WAMP
In comparison, WAMP has less number of extension.
WAMP packages contain MySql, PHP, and Apache; doesn’t have Perl.
Type CAsting
Example: If we will cast float number to an integer then the output will be the
number before the decimal. Means if we will cast 10.9 to an integer then the output
will be 10.
?>
WebTechnologies