0% found this document useful (0 votes)
2 views

wt-unit4-php

This document provides an overview of PHP programming, including its introduction, syntax, and key features such as variables, constants, data types, and operators. It covers how to create and run PHP scripts, as well as working with forms and databases. Additionally, it explains conditional statements and functions in PHP, making it a comprehensive guide for beginners in web technologies.

Uploaded by

hanusmurukutla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

wt-unit4-php

This document provides an overview of PHP programming, including its introduction, syntax, and key features such as variables, constants, data types, and operators. It covers how to create and run PHP scripts, as well as working with forms and databases. Additionally, it explains conditional statements and functions in PHP, making it a comprehensive guide for beginners in web technologies.

Uploaded by

hanusmurukutla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

lOMoARcPSD|15581981

WT unit4 - PHP

web technologies (Jawaharlal Nehru Technological University, Kakinada)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Hanumantharao Murukutla ([email protected])
lOMoARcPSD|15581981

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:

 PHP stands for PHP: Hypertext Preprocessor.


 PHP also called as Personal home Pages.
 PHP was developed in 1994 by Apache group.
 PHP is a server-side scripting language, like ASP
 It is mainly used for form handling and database access.
 PHP is a powerful tool for making dynamic and interactive Web pages.
 PHP scripts are executed on the server.
 PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL,
Generic ODBC, etc.)
 PHP is an open source software.PHP is free to download and use
 PHP files:
o PHP files can contain text, HTML tags and scripts
o PHP files are returned to the browser as plain HTML
o PHP files have a file extension of ".php", ".php3", or ".phtml"
 How does PHP Work?

Apache 1
2 Web Page
PHP Internet On
script Browser
3 5 6

PHP
4
MySql

DataBase MiddleWare

1. A web browser requests a page

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

2. The request is sent to the web server


3. If the page contains PHP, it is sent to the PHP parsing engine
4. The PHP parsing engine executes the PHP code and places the result in the page.
5. The Web server sends the HTML page back to the web browser
6. The browser displays the page
 Why PHP?
o PHP is an open source software.
o PHP has large number of library functions which makes it flexible.
o PHP is easy to learn and runs efficiently on the server side.
o PHP runs on different platforms (Windows, Linux, Unix, etc.)
o PHP is compatible with almost all servers used today (Apache, IIS, etc.)
o PHP is FREE to download from the official PHP resource: www.php.net
o PHP can easily integrate with over 25 databases.
o PHP is very popular for Web sites.
o PHP makes use of dynamic typing that means there is no need to declare the variables.
o If we click for view source on the web browser, we can never see the php code.

 Installing PHP:

Download PHP

o If the server supports PHP no need to do anything.


o Just create some .php files in the web directory, and the server will parse them.
Because it is free, most web hosts offer PHP support.
o However, if the server does not support PHP, we must install PHP.
o The site getting PHP for free: http://www.php.net/downloads.php

Download MySQL Database


o The Mysql DB is an open source software and can be easily downloaded from the
Internet.
o The site getting MySQL for free: http://www.mysql.com/downloads/

Download Apache Server:

o PHP requires the apache web server to execute its code.


o The Apache web server is an open source software and can be easily downloaded from
the Internet.
o The site getting Apache for free: http://httpd.apache.org/download.cgi

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

 Another approach which is the most efficient way to install Apache,PHP,MySql is


WAMPP Server(Windows Apache MySql,PHP,Perl).

 Creating PHP Script:

 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:

o In PHP, we use // to make a one-line comment

o /* and */ to make a comment block:

Example:

<html>
<body>

<?php
//This is a comment

/*
This is
a comment
block

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

*/
?>

</body>
</html>

 Running PHP Script

 MyComputer-->C:\xamp\htdocs\Create New Folder


 Start----->Run-->notepad-->Type Program---->Save ---->Programname.php in NewFolder
-->Save Type as AllFiles
 AnyBrowser--> http://localhost -> Our NewFolder will be appear -->Click on that --
>program name will be appear --->Click on the program for output

KeyWords:

and Or xor Not


while do for Foreach
switch Case default Break
if Else elseif Static
global continue function False

 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.

Syntax: $var_name = value;

 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

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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>

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

</html>
 Constants

 A constant is a name or an identifier for a simple value.


 A constant value cannot change during the execution of the script.
 By default a constant is case-sensitive.
 By convention, constant identifiers are always uppercase.
 A constant name starts with a letter or underscore, followed by any number of letters,
numbers, or underscores.
 If you have defined a constant, it can never be changed or undefined.
 To define a constant you have to use define() function.

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:

 For displaying Integer value, the Integer type is used.


 It is similar to Long in c.
 The size is 32 bit.
 Double Type:

 For displaying real values, double data type is used.


 It includes the numbers with decimal point, exponentiation, or both.

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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:

 There is no character data type in PHP. If the character has to be


represented then use string type itself.
 The string literals can be defined using either single or double quotes.
 Operators

Arithmetic Operators

Operator Description Example Result

+ Addition x=2 ,x+2 4

- Subtraction x=2 , 5-x 3

* Multiplication x=4 ,x*5 20

/ Division 15/5 3
5/2 2.5
% Modulus (division remainder) 5%2 1
10%8 2
10%2 0

++ Increment x=5 x=6


x++

-- Decrement x=5 x=4


x--

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

Assignment Operators:

OperatorExample Is The Same As

= 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:

Operator Description Example

== is equal to 5==8 returns false

!= is not equal 5!=8 returns true

> is greater than 5>8 returns false

< is less than 5<8 returns true

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

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

=== Strict comparison “5” == 5 returns true

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

“5” === 5 returns false

Logical Operators:

Operator Description Example

&& And x=6


y=3

(x < 10 && y > 1) returns true


|| Or x=6
y=3

(x==5 || y==5) returns false


! Not x=6
y=3

!(x==y) returns true

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>

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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:

Operator Description Example

?: Conditional Expression If Condition is true ? Then value X :


Otherwise value Y

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

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

 Strcmp(str1,str2):

o It compares the two strings.


o It is case sensitive.
o If this function returs 0 then two strings are equal.
o If this function returs >0 thenstring1>string2.
o If this function returs <0 thenstring1<string2.
Example:

<?php
echo strcmp("world","world");
?>

Output: 0

 strtolower(string): This converts the characters in string to lower case.

Example:

<?php
echo strtolower("HELLO!");

?>

 strtoupper(string): This converts the characters in string to upper case.

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>”;

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

?>

 Conditional Statements

In PHP we have the following conditional statements:

 if statement – This statement is used to execute some code only if a specified


condition is true
 if...else statement - This statement is used statement to execute some code if a
condition is true and another code if the condition is false
 if...elseif....else statement - This statement is used to select one of several blocks of
code to be executed
 switch statement - This statement is used to select one of many blocks of code to
be executed

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>

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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)

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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

In PHP, we have the following looping statements:

 while - loops through a block of code while a specified condition is true


 do...while - loops through a block of code once, and then repeats the loop as long as
a specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array.

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++;
}
?>

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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>

for Loop - loops through a block of code a specified number of times

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

Syntax:

for (init; condition; increment)


{
code to be executed;
}

Example:

<html>
<body>
<?php
for ($i=1; $i<=2; $i++)
{
for($j=1; $j<=10; $j++)
echo "$i * $j = " . $i*$j ."</br>";
}
?>
</body>
</html>

foreach : The foreach loop is used to loop through arrays.

Syntax:

foreach ($array as $value)


{
code to be executed;
}

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)

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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:

1. Numeric array - An array with a numeric index


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

Numeric array:

o A numeric array stores each array element with a numeric index.

o There are two methods to create a numeric array.

1. The index are automatically assigned (the index starts at 0):

Syntax: $array_name=array(10,20,30);

Example:

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

2. we assign the index manually:

Syntax: $array_name[]=value;

Example:

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

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

We can create an empty array using array construct.

Syntax: $array_name=array();

Associative array

 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.

Syntax:

$array_name=array(“key”=>”value”, “key”=>”value”);

Example:

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

 Functions

 The real power of PHP comes from its functions.


 In PHP, there are more than 700 built-in functions.

 To keep the script from being executed when the page loads, we must put it into function.

 A function will be executed by a call to the function.

 We may call a function from anywhere within a page.

Syntax:

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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";
}

echo "Hi! ";


sample();
?>
</font></center>
</body>
</html>
 Sending Parameters to a function:

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>

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

</body>
</html>
Returning value from the Function:

 Function that result a value must use the return statement.


 This statement specifies the value that will be returned to where the function was called.
 When using the return statement, the function will stop executing, and return the specified
value.

 Working with Forms

 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:

/*****************registration page - reg.html **************/

<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>

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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 page –display.php **************/

<?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>

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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:

 MySQL is the most popular open-source database system.


 MySql & PHP are Open source software .So they can be integrated each other.
 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.
 A query is a question or a request.

 Working with Database using MySql:

Connect ion of PHP to MySql involves 4 basic steps.


 Step1: Connect to the database server.
$con = mysqli_connect("servername","username","password");

 Step2: Selecting the data base


mysqli_select_db($con,"databasename");

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

 Step3: Data manipulation operations


mysqli_query($con “$query”);

 Step4: Closing the connection.


mysqli_close($con);

Creating Connection to My Sql Server:

o Before accessing the data in a database, we must create a connection to the database.

o In PHP, this is done with the mysql_connect() function.

Syntax:

mysql_connect(“servername”,”username”,”password”);

Example:

<?php
$con = mysqli_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
else
{
echo "connected.........";
}
?>

Creating Data Base:

o The CREATE DATABASE statement is used to create a database in MySQL.

Syntax:

mysql_query("CREATE DATABASE database_name",$con)

Example:

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

<?php

if($con = mysqli_connect("localhost", "root",""))


{
echo "Connected successfully";
echo"<br>";
}
$sql = "CREATE DATABASE rama";
if (mysqli_query($con,$sql)) {
echo "rama Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($con);
}

mysqli_close($con);
?>
Creating Data Base Tables:

 The CREATE TABLE statement is used to create a table in MySQL.


Syntax:
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
......................
)
Example:

<?php

//connection to server

$con = mysqli_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
else
{

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

echo "connected.........";
}

//database selection

if(mysqli_select_db($con,"rama"))
{
echo "selected";
}
else
{
echo " not selected";
}

//Creating Database Table

$sql = "CREATE TABLE students


(
Id int,
FirstName varchar(15),
LastName varchar(15),
Age int
)";

// Execute query

if(mysqli_query($con,$sql))
{
echo "table created";
}
else
{
echo "not created";
}
mysqli_close($con);

?>Inserting Data into tables:

 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.

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

1. INSERT INTO table_name


VALUES (value1, value2, value3,...)
2. INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Example:

<?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";
}

//Inserting data into Table

$query = "insert into students values( 1201,'Nalini','Durga',23)";

// Execute query

if(mysqli_query($con,$query))
{
echo "data inserted";
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

else
{
echo "not inserted";
}

//Closing Connection

mysqli_close($con);

?>

Updating Table data:

The UPDATE statement is used to modify data in a table.

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.........";

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

//database selection

mysqli_select_db( $con,"rama");

$query="UPDATE students SET Age=20 WHERE Id=1201";

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.

Syntax: DELETE FROM table_name WHERE some_column = some_value

Example:

<?php
//connection to server

$con = mysqli_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
else
{

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

echo "connected.........";
}

//database selection

mysqli_select_db( $con,"rama");

//deleting data

$query="delete from students";


if(mysqli_query($con,$query))
{
echo "successfully deleted";
}
else
{
echo "not deleted";
}

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>

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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");

//Creating Database Table

$sql = "CREATE TABLE student


(
Name varchar(15),

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

Emailid varchar(15) primary key,


Password varchar(15) not null,
ContactNo varchar(10)
)";

// Execute query

if(mysqli_query($con,$sql))
{
echo "table created";
}

//Inserting data into Table

$sql="INSERT INTO student VALUES


('$_POST[name]','$_POST[email]','$_POST[password]','$_POST[contact]')";

if(mysqli_query($con,$sql))
{
echo"Suceessfully Registered";
}
else
{
echo"Sorry! Registration Failed";
echo"Try again";
}

//Closing Connection

mysqli_close($con);

?>
</body>
</html>

Selecting Data from Database tables:

 The SELECT statement is used to select data from a database.


Example:

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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>

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

</html>

Validating User Credentials when he submits login Button:

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>

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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>

PHP include and require


Statements

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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 &copy; 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 require when the file is required by the application.

Use include when the file is not required and application should continue when file
is not found.

Use :

1. The method is used only for the modules(only to include


.pm type file)

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

2. The included objects are varified at the time of compilation.

Require:

1. The method is used for both libraries and modules.

2. The included objects are varified at the run time.

Types of Errors in PHP


The four types of PHP errors are:
1. Warning Error
2. Notice Error
3. Parse Error
4. Fatal Error

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.

The most common causes of warning errors are:


 Calling on an external file that does not exist in the directory
 Wrong parameters in a function

For instance:

<?php

echo "Warning error"';

include ("external_file.php");

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

?>

As there is no “external_file”, the output displays a message, notifying it failed to


include it. Still, it doesn’t stop executing the script.

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 "Notice error";

echo $b;
?>

In the script above, we defined a variable ($a), but called on an undefined


variable ($b). PHP executes the script but with a notice error message telling
you the variable is not defined.

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

Parse Error
Parse errors are caused by misused or missing symbols in a syntax. The
compiler catches the error and terminates the script.

Parse errors are caused by:


 Unclosed brackets or quotes
 Missing or extra semicolons or parentheses
 Misspellings

For example, the following script would stop execution and signal a parse error:

<?php

echo "Red";

echo "Blue";

echo "Green"
?>

It is unable to execute because of the missing semicolon in the third line.

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.

There are three (3) types of fatal errors:


1. Startup fatal error (when the system can’t run the code at installation)
2. Compile time fatal error (when a programmer tries to use nonexistent data)

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

3. Runtime fatal error (happens while the program is running, causing the code
to stop working completely)

For instance, the following script would result in a fatal error:

<?php

function sub()

$sub=6-1;

echo "The sub= ".$sub;

div();
?>

The output tells you why it is unable to compile, as in the image below:

XAMPP
 It has more extensions compared to WAMP.

 XAMPP package comes with Perl, Apache, MySql, and PHP.

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

 XAMPP is known for its clean, simple interface; ideal for beginners.

 XAMPP is supported by MAC as well as Windows/Linux.

WAMP
 In comparison, WAMP has less number of extension.

 WAMP packages contain MySql, PHP, and Apache; doesn’t have Perl.

 The interface is simple. There are several options attached to it,


programmers will appreciate it.

 WAMP is supported only by Linux and Windows.

Type CAsting

 (int), (integer) - cast to integer


 (bool), (boolean) - cast to boolean
 (float), (double), (real) - cast to float
 (string) - cast to string
 (array) - cast to array
 (object) - cast to object
 (unset) - cast to NULL (PHP 5)

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.

<?php $float_num = 10.9;

echo (int) $float_num;

?>

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

WebTechnologies

Downloaded by Hanumantharao Murukutla ([email protected])

You might also like