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

PHP Programming Unit 6

The document discusses forms in PHP programming. Forms allow users to input and submit data to a web server. PHP provides various options to create forms with different input elements and handle submitted data. It is important to validate user-submitted data for integrity and security. The document also explains how to create a basic HTML registration form with PHP, use the POST and GET methods to submit form data, and validate different form field types on the server-side.

Uploaded by

Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
220 views

PHP Programming Unit 6

The document discusses forms in PHP programming. Forms allow users to input and submit data to a web server. PHP provides various options to create forms with different input elements and handle submitted data. It is important to validate user-submitted data for integrity and security. The document also explains how to create a basic HTML registration form with PHP, use the POST and GET methods to submit form data, and validate different form field types on the server-side.

Uploaded by

Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 65

PHP PROGRAMMING

CREATING AND USING FORMS: To create a fully functional web application,


you need to be able to interact with your users. The common way to receive
information from web users is through a form. Generally we have several
options when dealing with forms. More specifically, you have control over
 what elements you want to provide to your user,
 how you handle the information passed to you, and
 In what format you choose to receive the data.
Obviously, when dealing with information that is passed from a user, it is
required that you spend some time validating the data passed to your script.
Issues such as user error and malicious scripts affect dealing with forms, so it
is important you maintain the integrity of whatever device you are using to
store information garnered from users.
WHAT IS FORM?
 When you login into a website or into your mail box, you are interacting
with a form.
 Forms are used to get input from the user and submit it to the web
server for processing.
 The diagram below illustrates the form handling process.

Prepared By: Dept Of CSE, RGMCET Page 1


PHP PROGRAMMING

PHP FORM
 A form is an HTML tag that contains graphical user interface items such
as input box, check boxes radio buttons etc.
 The form is defined using the <form>...</form> tags and GUI items are
defined using form elements such as input.
WHEN AND WHY WE ARE USING FORMS?
 Forms come in handy when developing flexible and dynamic applications
that accept user input.
 Forms can be used to edit already existing data from the database
CREATE A FORM
We will use HTML tags to create a form. The list of things used to create a form
is
 Opening and closing form tags <form>…</form>
 Form submission type POST or GET
 Submission URL that will process the submitted data
 Input fields such as input boxes, text areas, buttons, checkboxes etc.
 The code below creates a simple registration form
<html>
<head><title>Registration Form</title></head>
<body>
<form action="registration_form.php" method="POST">
First name: <input type="text" name="firstname"> <br>
Last name: <input type="text" name="lastname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Viewing the above code in a web browser displays the following form.

Prepared By: Dept Of CSE, RGMCET Page 2


PHP PROGRAMMING

Here,
 <form…>…</form> are the opening and closing form tags
 action="registration_form.php" method="POST"> specifies the destination
URL and the submission type.
 First/Last name: are labels for the input boxes
 <input type=”text”…> are input box tags
 <br> is the new line tag
 <input type="submit" value="Submit"> is the button that when clicked
submits the form to the server for processing
UNDERSTANDING COMMON FORM ISSUES
When dealing with forms, the most important aspect to remember is that you
are limited to a certain variety of fields that can be applied to a form. The fields
that have been created are non-negotiable and work in only the way they were
created to work. It is important, therefore, to fully understand what is available
and how best to use the form features to your advantage.
Element Description
TEXT INPUT A simple text box
PASSWORD INPUT A text box that hides the characters inputted
HIDDEN INPUT A field that does not show on the form but can
contain data
SELECT A drop-down box with options
LIST A select box that can have multiple options
selected

Prepared By: Dept Of CSE, RGMCET Page 3


PHP PROGRAMMING

CHECKBOX A box that can be checked


RADIO A radio button that can act as a choice
TEXTAREA A larger box that can contain paragraph-style
entries
FILE An element that allows you to browse your
computer for a file
SUBMIT A button that will submit the form
RESET A button that will reset the form to its original
state

SUBMITTING THE FORM DATA TO THE SERVER


When dealing with forms, you must specify the way that the information
entered into the form is transmitted to its destination (method=""). The two
ways available to a web developer are GET and POST. PHP POST method
POST: When Sending data using the POST method is quite a bit more secure
(because the method cannot be altered by appending information to the
address bar) and can contain as much information as you choose to send.
Example:
The example below displays a simple HTML form with two input fields and a
submit button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

Prepared By: Dept Of CSE, RGMCET Page 4


PHP PROGRAMMING

When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php". The form data is
sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables.
WELCOME.PHP:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
Output: Welcome Uday
Your email address is [email protected]

GET: When sending data using the GET method, all fields are appended to the
Uniform Resource Locator (URL) of the browser and sent along with the
address as data. Sending data using the GET method means that fields are
generally capped at 150 characters, which is certainly not the most effective
means of passing information. It is also not a secure means of passing data,
because many people know how to send information to a script using an
address bar.
Example
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
WELCOME_GET.PHP:

Prepared By: Dept Of CSE, RGMCET Page 5


PHP PROGRAMMING

<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
GET VS POST METHODS
POST
 Values not visible in the URL.
 Has not limitation of the length of the values since they are submitted via
the body of HTTP.
 Has lower performance compared to PHP_GET method due to time spent
encapsulation the PHP_POST values in the HTTP body
 Supports many different data types such as string, numeric, binary etc.

 Results cannot be book marked

GET
 Values visible in the URL
 Has limitation on the length of the values usually 255 characters. This is
because the values are displayed in the URL. Note the upper limit of the
characters is dependent on the browser.
 Has high performance compared to POST method dues to the simple
nature of appending the values in the URL.
Prepared By: Dept Of CSE, RGMCET Page 6
PHP PROGRAMMING

 Supports only string data types because the values are displayed in the
URL
 Results can be book marked due to the visibility of the values in the URL

VALIDATING FORM INPUT:


Validation means check whether the field is filled or not in the proper way.
There are two types of validation are available in PHP.
Client-Side Validation: Validation is performed on the client machine web
browsers.
Server Side Validation: Validation is performed on the server machine.

Some of validation rules for field:

Field Validation Rules

Name Should required letters and white-spaces

Email Should required @ and .

Website Should required a valid URL

Radio Must be selectable at least once

Prepared By: Dept Of CSE, RGMCET Page 7


PHP PROGRAMMING

Check Box Must be checkable at least once

Drop Down menu Must be selectable at least once

EXAMPLES:
Valid URL: Below code shows validation of URL
$website = input($_POST["site"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-
a-z0-9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
Above syntax will verify whether a given URL is valid or not. It should allow
some keywords as https, ftp, www, a-z, 0-9,..etc..
Valid Email: Below code shows validation of Email address
$email = input($_POST["email"]);
if (!filter_var ($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid format and please re-enter valid email";
}
Above syntax will verify whether given Email address is well-formed or not.if it
is not, it will show an error message.

Example Program(Username, Password and Email validation)


<html>
<body>
<form action="validate.php" method="post">
username:<input type="text"name="username">
password:<input type="text" name="password" >
E-mail:<input type="text" name="email" >
<input class="submit" name="submit" type="submit" value="Submit">
</form>
</body>
</html>
VALIDATE.PHP
<?php

Prepared By: Dept Of CSE, RGMCET Page 8


PHP PROGRAMMING

if(isset($_POST['submit']))
{
if (empty($_POST["username"]))
echo "Name is required"."<br>";
else
{
$name = $_POST["username"];
if (!preg_match("/^[a-zA-Z ]*$/",$name))
echo "Only letters and white space allowed"."<br>";
}
if (empty($_POST["password"]))
echo "Password is required"."<br>";
else
{
$pass = $_POST["password"];
if (!preg_match("/^[a-zA-Z ]*$/",$pass))
echo "Only letters and white space allowed"."<br>";
}
if (empty($_POST["email"]))
echo "Email is required"."<br>";
else
{
$email = $_POST["email"];
if (!preg_match("/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/",$email))
echo "Invalid email format"."<br>";
or
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
echo "Invalid email format"."<br>";
}

}
?>
Example program2:
<html>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

Prepared By: Dept Of CSE, RGMCET Page 9


PHP PROGRAMMING

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
$nameErr = "Name is required";
else
$name = test_input($_POST["name"]);
if (empty($_POST["email"]))
$emailErr = "Email is required";
else
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
$emailErr = "Invalid email format";
if (empty($_POST["website"]))
$website = "";
else
$website = test_input($_POST["website"]);
if (empty($_POST["comment"]))
$comment = "";
else
$comment = test_input($_POST["comment"]);
if (empty($_POST["gender"]))
$genderErr = "Gender is required";
else
$gender = test_input($_POST["gender"]);
}
function test_input($data)
{
$data = trim($data);

Prepared By: Dept Of CSE, RGMCET Page 10


PHP PROGRAMMING

$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method = "post" action = "<?php echo htmlspecialchars
($_SERVER["PHP_SELF"]); ?>">
Name : <input type = "text" name = "name">
E-mail: <input type = "text" name = "email">
Time: <input type = "text" name = "website">
Classes: <textarea name="comment"rows="5"cols= "40"></textarea>
Gender:
<input type = "radio" name = "gender" value = "female">Female
<input type = "radio" name = "gender" value = "male">Male
<input type = "submit" name = "submit" value = "Submit">
</form>
<?php
echo "<h2>Your given values are as:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

Prepared By: Dept Of CSE, RGMCET Page 11


PHP PROGRAMMING

</body>
</html>
WORKING WITH MULTIPAGE FORMS: Sometimes you will need to collect
values from more than one page. Most developers do this for the sake of clarity.
By providing forms on more than one page, you can separate blocks of
information and thus create an ergonomic experience for the user. The
problem, therefore, is how to get values from each page onto the next page and
finally to the processing script. Being the great developer that you are, you can
solve this problem and use the hidden input form type. When each page loads,
you must load the values from the previous pages into hidden form elements
and submit them
PAGE1.HTML
<html >
<head><title> Page1</title></head>
<body>
<form action=" page2.php" method="post">
Your Name: <input type="text"name="name" maxlength="150" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
PAGE2.HTML
<html>
<head><title> Page2</title></head>
<body>
<form action="page3.php" method="post">
Selection: <select name="selection">
<option value="nogo">make a selection...</option>
<option value="1">Choice 1</option>
<option value="2">Choice 2</option>
<option value="3">Choice 3</option>
</select><br /><br />
<input type="hidden"name="name"value="<?php echo $_POST['name']; ?>" />
<input type="submit" value="Submit" />
</form>
</body>

Prepared By: Dept Of CSE, RGMCET Page 12


PHP PROGRAMMING

</html>
PAGE3.HTML
<html>
<head><title> Page3</title></head>
<body>
<form action="page4.php" method="post">
Your Email: <input type="text" name="email" maxlength="150" /><br />
<input type="hidden"name="name"value="<?php echo $_POST['name']; ?>" />
<input type="hidden"name="selection"value="<?php echo_POST['selection'];?
>" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

PAGE4.PHP
<html>
<head><title>Page4</title></head>
<body>
<?php
echo "Your Name: " . $_POST['name'] . "<br />";
echo "Your Selection: " . $_POST['selection'] . "<br />";
echo "Your Email: " . $_POST['remail'] . "<br />";
?>
<a href="page1.php">Try Again</a>
</body>
</html>
PREVENTING MULTIPLE SUBMISSIONS OF A FORM: One possible
occurrence that happens often is that users become impatient when waiting for
your script to do what it is doing, and hence they click the submit button on a
form repeatedly. This can cause great damage on your script because, while
the user may not see anything happening, your script is probably going ahead
with whatever it has been programmed to do. If a user continually hits the
submit button on a credit card submittal form, their card may be charged
multiple times if the developer has not taken the time to validate against such
an eventuality. You can deal with multiple submittal validation in two ways.

Prepared By: Dept Of CSE, RGMCET Page 13


PHP PROGRAMMING

PREVENTING MULTIPLE SUBMISSIONS ON THE SERVER SIDE: we prefer


to use a session-based method. Basically, once the submit button has been
clicked, the server logs the request from the individual user. If the user
attempts to resubmit a request, the script notes a request is already in motion
from this user and denies the subsequent request. Once the script has finished
processing, the session is unset, and you have no more worries.
<html>
<body>
<form action="process.php" method="post">
Your Name:<input type="text" name="name" ><br />
<input type="submit" value="Submit" >
</form>
</body>
</html>
PROCESS.PHP
<?php
session_start ();
if (!isset ($_SESSION['processing']))
$_SESSION['processing'] = false;
if ($_SESSION['processing'] == false)
{
$_SESSION['processing'] = true;
for ($i = 0; $i < 2000000; $i++)
{
//Thinking...
}
if ($file = fopen ("test.txt","w+"))
fwrite ($file, "Processing");
else
echo "Error opening file.";
echo $_POST['yourname'];
unset ($_SESSION['processing']);
}
?>
PREVENTING MULTIPLE SUBMISSIONS ON THE CLIENT SIDE: Handling
multiple submittals from a client-side perspective is actually much simpler

Prepared By: Dept Of CSE, RGMCET Page 14


PHP PROGRAMMING

than doing it on the server side. With well-placed JavaScript, you can ensure
that the browser will not let the submittal go through more than once.
<html>
<head>
<script language="javascript" type="text/javascript">
function checkandsubmit()
{ //Disable the submit button.
document.test.submitbut.disabled = true;
//Then submit the form.
document.test.submit();
}
</script>
</head>
<body>
<form action="process.php"method="post"name="test"onsubmit="return
checkandsubmit ()">
Your Name: <input type="text" name="name" maxlength="150" /><br />
<input type="submit"value="Submit"id="submitbut" name"submitbut"/>
</form>
</body>
</html>
PROCESS.PHP
<?php
for ($i = 0; $i < 2000000; $i++)
{
//Thinking...
}
if ($file = fopen ("test.txt","w+"))
fwrite ($file, "Processing");
else
echo "Error opening file.";
echo $_POST['yourname'];
?>
PROCESSING THE REGISTRATION FORM DATA
 The registration form submits data to itself as specified in the action
attribute of the form.
 When a form has been submitted, the values are populated in the
$_POST super global array.

Prepared By: Dept Of CSE, RGMCET Page 15


PHP PROGRAMMING

 We will use the PHP isset function to check if the form values have been
filled in the $_POST array and process the data.
 We will modify the registration form to include the PHP code that
processes the data. Below is the modified code
<html>
<head><title>Registration Form</title></head>
<body>
<?php if (isset($_POST['form_submitted'])): ?>
//this code is executed when the form is submitted
<h2>Thank You <?php echo $_POST['firstname']; ?> </h2>
<p>You have been registered as
<?php echo $_POST['firstname'] . ' ' . $_POST['lastname']; ?>
</p>
<p>Go <a href="/registration_form.php">back</a> to the form</p>
<?php else: ?>
<h2>Registration Form</h2>
<form action="registration_form.php" method="POST">
First name:
<input type="text" name="firstname">
<br> Last name:
<input type="text" name="lastname">
<input type="hidden" name="form_submitted" value="1" />
<input type="submit" value="Submit">
</form>
<?php endif; ?>
</body>
</html>
Here,

Prepared By: Dept Of CSE, RGMCET Page 16


PHP PROGRAMMING

 <?php if (isset($_POST['form_submitted'])): ?> checks if the


form_submitted hidden field has been filled in the $_POST[] array and
display a thank you and first name message.
 If the form_submitted field hasn’t been filled in the $_POST[] array, the
form is displayed.

PHP & MYSQL


What is MySQL?
MySQL is open source Relational Database Management System (RDBMS) that
uses Structured Query Language (SQL), which is used for adding ,accessing
and managing content in database.It is the most popular database system
used with PHP. MySQL is developed, distributed, and supported by Oracle
Corporation.
 The data in a MySQL database are stored in a table which consists of
columns and rows.
 MySQL is a database system that runs on a server.
 MySQL is ideal for both small and large applications.
 MySQL is very fast, reliable and easy to use database system.
 MySQL compiles on a number of platforms.
PHPMYADMIN: PHPMYADMIN is a open source platform used for
administering MySQL with a web browser. By using PHPMYADMIN we can
perform database operations such as create, alter, drop, delete, import and
export database tables. PHPMYADMIN is available with XAMPP installation.
For accessing PHPMYADMIN we can use the following URL address
https://localhost/phpmyadmin
 It is providing number of options to manage MySQL database tables.
Insert: Using this option, we can insert a record or set of records.
Browse: Using this option, we can display all records of tables.

Prepared By: Dept Of CSE, RGMCET Page 17


PHP PROGRAMMING

Structure: To change the structure of table. If you want to add a column or


delete existing columns, to add a constraint or delete existing constraints we
can use this option.
SQL: To execute SQL queries.
Search: Using this option, we can search tables records in ascending or
descending order based on specified column.
Operations: To change the options of table like table name, storage engine,
etc.
Export: Using this option, we can export table data as SQL file, pdf file, xml
file, etc.
Import: Using this option, we can import exported SQL file into current
database.
Empty: Using this option, we can delete all records of table.
Drop: Using this option, we can drop structure of table.
DATATYPES
In MySQL 3 types of data types available. They are
a. Numeric data types
b. String data types
c. Date and Time data types
a. Numeric data types
This data type can store numeric values. It is divided into 2 types.
1. Signed data type
2. Unsigned data type

Minimum Maximum
Storage Minimum Value Maximum Value
Type (Bytes) Value Signed Unsigned Value Signed Unsigned
TINYINT 1 -128 0 127 255
SMALLINT 2 -32768 0 32767 65535
MEDIUMINT 3 -8388608 0 8388607 16777215

Prepared By: Dept Of CSE, RGMCET Page 18


PHP PROGRAMMING

Minimum Maximum
Storage Minimum Value Maximum Value
Type (Bytes) Value Signed Unsigned Value Signed Unsigned
INT 4 -2147483648 0 2147483647 4294967295
BIGINT 8 -263 0 263-1 264-1

 FLOAT (10,2)
This data type can store decimal values. We can store total digits 10 and
after decimal 2 digits.
 DOUBLE (16,4)
We can store total number of digits are 16 and after decimal 4.
 DECIMAL
Same as floating point number but cannot be unsigned.

b. String data types


String Types Description
 CHAR A fixed-length nonbinary (character) string
 VARCHAR A variable-length non-binary string
 BINARY A fixed-length binary string
 VARBINARY A variable-length binary string
 TINYBLOB A very small BLOB (binary large object)
 BLOB A small BLOB
 MEDIUMBLOB A medium-sized BLOB
 LONGBLOB A large BLOB
 TINYTEXT A very small non-binary string
 TEXT A small non-binary string
 MEDIUMTEXT A medium-sized non-binary string
 LONGTEXT A large non-binary string

Prepared By: Dept Of CSE, RGMCET Page 19


PHP PROGRAMMING

String Types Description


 ENUM An enumeration; each column value may be assigned one
enumeration member
 SET A set; each column value may be assigned zero or
more SET members
c. Date and Time data types
Date and Description
Time Types
 DATE A date value in YYYY-MM-DD format
 TIME A time value in hh:mm:ss format
 DATETIME A date and time value in YYYY-MM-DD hh:mm:ssformat
 TIMESTAMP A timestamp value in YYYY-MM-DD hh:mm:ss format
 YEAR A year value in YYYY or YY format

ESTABLISH A CONNECTION WITH DATABASE:


mysqli_connect(): Using this function, we can establish a connection with
MySQL database. Arguments are server name, user id and password.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = mysqli_connect($servername, $username, $password);

if (!$conn)
die("Connection failed: " . mysqli_connect_error());
echo "Connected successfully";
?>
Or
<?php
$con=mysql_connect(localhost”,”root”,””);

Prepared By: Dept Of CSE, RGMCET Page 20


PHP PROGRAMMING

if($con)
echo “connected”;
else
echo “Not connected”;
?>
Example: To create a database in MySQL
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn)
die("Connection failed: " . mysqli_connect_error());
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql))
echo "Database created successfully";
else
echo "Error creating database: " . mysqli_error($conn);
mysqli_close($conn);
?>
Example: To select a database in MySQL
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn)
die("Connection failed: " . mysqli_connect_error());

Prepared By: Dept Of CSE, RGMCET Page 21


PHP PROGRAMMING

$sql =mysql_select_db($conn,”myDB”);
if (mysqli_query($conn, $sql))
echo "Database selected successfully";
else
echo "Error selecting database: " . mysqli_error($conn);
mysqli_close($conn);
?>
Example: To create a table in MySQL
<?php
$link = mysqli_connect("localhost", "root", "");
if($link == false)
die("ERROR: Could not connect. " . mysqli_connect_error());
$sql = "CREATE TABLE persons(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
email VARCHAR(70) NOT NULL UNIQUE )";
if(mysqli_query($link, $sql))
echo "Table created successfully.";
else
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
mysqli_close($link);
?>
Example: To insert a record in a table
<?php
$link = mysqli_connect("localhost", "root", "", "");
if($link == false)
die("ERROR: Could not connect. " . mysqli_connect_error());

Prepared By: Dept Of CSE, RGMCET Page 22


PHP PROGRAMMING

$sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('Peter',


'Parker', '[email protected]')";
if(mysqli_query($link, $sql))
echo "Records inserted successfully.";
else
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
mysqli_close($link);
?>
 mysql_error(): To get error message if any occurred at the time of MySQL
statement execution.
 mysql_errno(): To get error number if any occurred at the time of SQL
statement execution.
<?php
$con=mysqli_connect("localhost","root","");
if (!$con)
{
die("Connection error: " . mysqli_connect_errno());
}
?>
Selecting Data From Database Tables
The SQL SELECT statement is used to select the records from database tables.
<?php
$link = mysqli_connect("localhost", "root", "");
if($link == false)
die("ERROR: Could not connect. " . mysqli_connect_error());
$sql = "SELECT * FROM persons";
if($result = mysqli_query($link, $sql))
{

Prepared By: Dept Of CSE, RGMCET Page 23


PHP PROGRAMMING

if(mysqli_num_rows($result) > 0)
{
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
}
else
{

echo "No records matching your query were found.";


}
}

Prepared By: Dept Of CSE, RGMCET Page 24


PHP PROGRAMMING

else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
Filtering the Records
The WHERE clause is used to extract only those records that fulfill a specified
condition.
<?php
$link = mysqli_connect("localhost", "root", "");
if($link === false)
die("ERROR: Could not connect. " . mysqli_connect_error());
$sql = "SELECT * FROM persons WHERE first_name='john'";
if($result = mysqli_query($link, $sql))
{
if(mysqli_num_rows($result) > 0)
{
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";

Prepared By: Dept Of CSE, RGMCET Page 25


PHP PROGRAMMING

echo "<td>" . $row['id'] . "</td>";


echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Close result set
mysqli_free_result($result);
}
else
{
echo "No records matching your query were found.";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
Ordering the Result Set
The ORDER BY clause can be used in conjugation with the SELECT statement
to see the data from a table ordered by a specific field. The ORDER BY clause
lets you define the field name to sort against and the sort direction either
ascending or descending.
<?php
$link = mysqli_connect("localhost", "root", "");

Prepared By: Dept Of CSE, RGMCET Page 26


PHP PROGRAMMING

if($link === false)


die("ERROR: Could not connect. " . mysqli_connect_error());
$sql = "SELECT * FROM persons ORDER BY first_name";
if($result = mysqli_query($link, $sql))
{
if(mysqli_num_rows($result) > 0)
{
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "No records matching your query were found.";

Prepared By: Dept Of CSE, RGMCET Page 27


PHP PROGRAMMING

}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
Updating Database Table Data
The UPDATE statement is used to change or modify the existing records in a
database table. This statement is typically used in conjugation with the
WHERE clause to apply the changes to only those records that matches
specific criteria.
<?php
$link = mysqli_connect("localhost", "root", "");
if($link === false)
die("ERROR: Could not connect. " . mysqli_connect_error());
$sql = "UPDATE persons SET email='[email protected]' WHERE
id=1";
if(mysqli_query($link, $sql))
echo "Records were updated successfully.";
else
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
mysqli_close($link);
?>
Deleting Database Table Data
Just as you insert records into tables, you can delete records from a table
using the SQL DELETE statement. It is typically used in conjugation with the

Prepared By: Dept Of CSE, RGMCET Page 28


PHP PROGRAMMING

WHERE clause to delete only those records that matches specific criteria or
condition.
<?php
$link = mysqli_connect("localhost", "root", "");
if($link === false)
die("ERROR: Could not connect. " . mysqli_connect_error());
$sql = "DELETE FROM persons WHERE first_name='John'";
if(mysqli_query($link, $sql))
echo "Records were deleted successfully.";
else
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
mysqli_close($link);
?>

Prepared By: Dept Of CSE, RGMCET Page 29


PHP PROGRAMMING

SUPER GLOBAL VARIABLES


 PHP super global variables are used to access global variables from
anywhere in the PHP script.
 PHP Super global variables are accessible inside the same page that
defines it, as well as outside the page.
 While local variable’s scope is within the page that defines it.
 These are specially-defined array variables in PHP that make it easy for
you to get information about a request or its context. The super global
are available throughout your script.
 These variables can be accessed from any function, class or any file
without doing any special task such as declaring any global variable etc.
They are mainly used to store and get information from one page to
another in an application.
 The list of super global variables available in PHP are:
 $GLOBALS

Prepared By: Dept Of CSE, RGMCET Page 30


PHP PROGRAMMING

 $_SERVER
 $_REQUEST
 $_GET
 $_POST
 $_SESSION
 $_COOKIE
 $_FILES
 $_ENV
1. $GLOBALS
 It is a super global variable which is used to access global variables from
anywhere in the PHP script.
 PHP stores all the global variables in array $GLOBALS [ ] it consist of an
array which have an index that holds the global variable name, which
can be accessed.
Example:
<?php
$x = 300;
$y = 200;
function multiplication()
{
$GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];
}
multiplication();
echo $z;
?>
Output:
60000
2. $_SERVER

Prepared By: Dept Of CSE, RGMCET Page 31


PHP PROGRAMMING

 It is a PHP super global variable that stores the information about


headers, paths and script locations (i.e., complete information of web
server and web browser).
 Some of these elements are used to get the information from the super
global variable $_SERVER.
Example:
<?php
print_r($_SERVER);
?>
Output:
All server related variables will be shown

The following table lists the most important elements that can go inside
$_SERVER:

Element/Code Description

$_SERVER['PHP_SELF'] Returns the filename of the


currently executing script

$_SERVER['GATEWAY_INTERFACE'] Returns the version of the


Common Gateway Interface (CGI)
the server is using

$_SERVER['SERVER_ADDR'] Returns the IP address of the


host server

Prepared By: Dept Of CSE, RGMCET Page 32


PHP PROGRAMMING

$_SERVER['SERVER_NAME'] Returns the name of the host


server (such as
www.w3schools.com)

$_SERVER['SERVER_SOFTWARE'] Returns the server identification


string (such as Apache/2.2.24)

$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of


the information protocol (such as
HTTP/1.1)

$_SERVER['REQUEST_METHOD'] Returns the request method used


to access the page (such as
POST)

$_SERVER['REQUEST_TIME'] Returns the timestamp of the


start of the request (such as
1377687496)

$_SERVER['QUERY_STRING'] Returns the query string if the


page is accessed via a query
string

$_SERVER['HTTP_ACCEPT'] Returns the Accept header from


the current request

Prepared By: Dept Of CSE, RGMCET Page 33


PHP PROGRAMMING

$_SERVER['HTTP_ACCEPT_CHARSET'] Returns the Accept_Charset


header from the current request
(such as utf-8,ISO-8859-1)

$_SERVER['HTTP_HOST'] Returns the Host header from the


current request

$_SERVER['HTTP_REFERER'] Returns the complete URL of the


current page (not reliable
because not all user-agents
support it)

$_SERVER['HTTPS'] Is the script queried through a


secure HTTP protocol

$_SERVER['REMOTE_ADDR'] Returns the IP address from


where the user is viewing the
current page

$_SERVER['REMOTE_HOST'] Returns the Host name from


where the user is viewing the
current page

$_SERVER['REMOTE_PORT'] Returns the port being used on


the user's machine to
communicate with the web server

Prepared By: Dept Of CSE, RGMCET Page 34


PHP PROGRAMMING

$_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname


of the currently executing script

$_SERVER['SERVER_ADMIN'] Returns the value given to the


SERVER_ADMIN directive in the
web server configuration file (if
your script runs on a virtual
host, it will be the value defined
for that virtual host) (such as
[email protected])

$_SERVER['SERVER_PORT'] Returns the port on the server


machine being used by the web
server for communication (such
as 80)

$_SERVER['SERVER_SIGNATURE'] Returns the server version and


virtual host name which are
added to server-generated pages

$_SERVER['PATH_TRANSLATED'] Returns the file system based


path to the current script

$_SERVER['SCRIPT_NAME'] Returns the path of the current


script

$_SERVER['SCRIPT_URI'] Returns the URI of the current

Prepared By: Dept Of CSE, RGMCET Page 35


PHP PROGRAMMING

page

3. $_REQUEST
 The PHP $_REQUEST variable contains the contents of both $_GET,
$_POST, and $_COOKIE.
 The PHP $_REQUEST variable can be used to get the result from form
data sent with both the GET and POST methods. By using this we can
also get values of cookie and query string.
 Query string is small amount of data on URL address followed by ?
symbol.
 Along with form data, if we want to transfer some extra information from
one page to another page at the time of redirection, we can use query
string.
 Query string can be passed in two ways:
1. Query string as name and value.
2. Query string with only value.
 Using $_REQUEST, we can get value of query string if it is combination
of name and value.
Example:
Abc.html
<a href=”p1.php? sno=100 & un=”scott”>click</a>
p1.php
<?php
echo $REQUEST[“sno”];
echo $REQUEST[“un”];
?>
4. $_GET

Prepared By: Dept Of CSE, RGMCET Page 36


PHP PROGRAMMING

 It is an array data type. Total number of elements is equal to total


number of posted values.
 Elements keys are control names and element values are control values.
 The $_GET variable is used to collect values from a form with
method="get".
 Information sent from a form with the GET method is visible to everyone
(it will be displayed in the browser's address bar) and it has limits on the
amount of information to send (max. 100 characters).
Example:
Form.html
<form method=”GET” action=”p1.php”>
<input type=”textbox” name=”t1” ><br>
<input type=”textbox” name=”t2” ><br>
<input type=”submit” name=”b1” value=”click” ><br>
</form>
P1.php
<?php
print_r($_GET);
echo $_GET[“t1”];
echo $_GET[“t2”];
echo $_GET[“b1”];
?>
Output:
Array([t1]->uday [t2]->cse [sub]->click)
uday cse click
5. $_POST
 The $_POST variable is an array of variable names and values sent by
the HTTP POST method.

Prepared By: Dept Of CSE, RGMCET Page 37


PHP PROGRAMMING

 The $_POST variable is used to collect values from a form with


method="post".
 Information sent from a form with the POST method is invisible to others
and has no limits on the amount of information to send.
 If more than one submit controls are there in the form, then only one
control should pass to server.
Example:
Form.php
<?php
$txt1=$_POST[‘t1’];
$txt2=$_POST[‘t2’];
echo “value is”.$txt1;
echo “value is”.$txt2;
?>
<form method=”GET” action=” ”>
<input type=”textbox” name=”t1” ><br>
<input type=”textbox” name=”t2” ><br>
<input type=”submit” name=”b1” value=”click” ><br>
</form>
NOTE: In the above example, the php script is first executed. Since the form is
not yet executed, the values are undefined for txt1 and txt2 variables. Thus to
eliminate this problem, we rewrite the code as:
<?php
if(isset($_POST[‘b1]))
{
error_reporting(E_ALL);
$txt1=$_POST[‘t1’];
$txt2=$_POST[‘t2’];

Prepared By: Dept Of CSE, RGMCET Page 38


PHP PROGRAMMING

echo “value is”.$txt1;


echo “value is”.$txt2;
}
?>
<form method=”GET” action=” ”>
<input type=”textbox” name=”t1” ><br>
<input type=”textbox” name=”t2” ><br>
<input type=”submit” name=”b1” value=”click” ><br>
</form>
How to post the values in the textbox after reloading of form?
<?php
if(isset($_POST[‘b1]))
{
error_reporting(E_ALL);
$txt1=$_POST[‘t1’];
$txt2=$_POST[‘t2’];
echo “value is”.$txt1;
echo “value is”.$txt2;
}
?>
<form method=”GET” action=” ”>
<input type=”textbox” name=”t1” value=”<?php echo $_POST[‘t1’]; ?>”><br>
<input type=”textbox” name=”t2” value=”<?php echo $_POST[‘t2’]; ?>”><br>
<input type=”submit” name=”b1” value=”click” ><br>
</form>
6. $_SESSION

Prepared By: Dept Of CSE, RGMCET Page 39


PHP PROGRAMMING

 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.
 It is same as cookies used to maintain state of application.
 Data of session storing in server memory location can be accessed from
any webpage of that application.
 Using this variable we can create and access sessions.
 By default, we cannot access sessions of one page from another page. To
access sessions, we need to initialize them in global memory locations.
 There are two ways to initialize sessions in global memory locations:
A. Change session auto_start configuration setting value as 1. This is used
to initialize sessions.
B. Use session_start() in the program from where you want to access
sessions.
SESSION ID:
 Session Id is an alphanumeric string generated by webserver when user
sends a request to server.
 If user sends a request, server checks the request whether it contains
session id or not. If request doesn.t contain session id then server
creates a new session id.
 It is alphanumeric string. At the same time in server temporary memory
location, a file will be created to maintain the session data of user. File
name is same as session id with prefix word sess_.
 Server sends a response to client system along with session id and
storing that session id as in-memory cookie. The name of cookie is
PHPSESSID and the value is session id.
 From next request onwards same session id transfers between browser
and server.

Prepared By: Dept Of CSE, RGMCET Page 40


PHP PROGRAMMING

 Server is using session id to identify users. If user close browser in-


memory cookie will be destroyed. Later, if wser sends request to the
server, server sends the request without session cookie. Again browser
will create new session id.
i. session_id()
ii. session_unregister()
iii. session_unset()
iv. session_destroy()
v.
PHP Session Variables
 When you are working with an application, you open it, do some changes
and then you close it. This is much like a Session. The computer knows
who you are. It knows when you start the application and when you end.
 But on the internet there is one problem: the web server does not know
who you are and what you do because the HTTP address doesn't
maintain state.
 A PHP session solves this problem by allowing you to store user
information on the server for later use (i.e. username, shopping items,
etc). However, session information is temporary and will be deleted after
the user has left the website. If you need a permanent storage you may
want to store the data in a database.
 Sessions work by creating a unique id (UID) for each visitor and store
variables based on this UID. The UID is either stored in a cookie or is
propagated in the URL.
Starting a PHP Session
 Before you can store user information in your PHP session, you must
first start up the session.
 The session_start() function must appear BEFORE the <html> tag:

Prepared By: Dept Of CSE, RGMCET Page 41


PHP PROGRAMMING

<?php session_start(); ?>


<html>
<body>
</body>
</html>

 The code above will register the user's session with the server, allow you
to start saving user information, and assign a UID for that user's
session.

Storing a Session Variable


 The correct way to store and retrieve session variables is to use the PHP
$_SESSION variable:
Example:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>

Prepared By: Dept Of CSE, RGMCET Page 42


PHP PROGRAMMING

Output:
Pageviews=1
In the example below, we create a simple page-views counter. The isset()
function checks if the "views" variable has already been set. If "views" has been
set, we can increment our counter. If "views" doesn't exist, we create a "views"
variable, and set it to 1:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session
 If you wish to delete some session data, you can use the unset() or the
session_destroy() function.
 The unset() function is used to free the specified session variable:
 The session_destroy() will reset your session and you will lose all your
stored session data.
<?php
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy()
function:
<?php
session_destroy();
?>

Prepared By: Dept Of CSE, RGMCET Page 43


PHP PROGRAMMING

7. $_COOKIE
 Cookie is a state management object used to maintain state of
application.
 Data of cookie will store in browser memory location. This data can be
accessed from any web page in an application.
 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 a browser, it will send the cookie too. With PHP, you
can both create and retrieve cookie values.
 Cookie is state
 A cookie is often used to identify a user.
 Cookies are divided into two types:
1. In-memory cookie
We create a cookie in client machine without explicit expiry time is called in-
memory cookie. Data of this cookie will delete after closing web browser.
2. Persistence cookie
We create a cookie in client machine with explicit expiry time is called
persistence cookie. It stores data in hard disk memory location, that data
will destroy after its lifetime is completed.
 Every browser contains memory locations in RAM and hard disks. Hard
disk memory allocates when the browser is installed. Ram memory
allocates when we open the first window in browser.
 RAM memory deallocates when we close all windows of browser. Hard
disk memory deallocates after uninstallation of browser.
 Memory of one browser cannot be accessible by another browser.
 All windows of in browser can share common memory allocation.
 Every website contains a folder in browser. Cookies of that website will
store in that folder only. This is the reason cookies of one website cannot

Prepared By: Dept Of CSE, RGMCET Page 44


PHP PROGRAMMING

be accessed by the cookies of another website. This folder will be created


when website is opening in browser.
HOW TO CREATE A COOKIE?
 The setcookie() function is used to create a cookie in client machine.
 It must appear BEFORE the <html> tag.
 The value of the cookie is automatically URLencoded when sending the
cookie, and automatically decoded when received (to prevent
URLencoding, use setrawcookie() instead).
Syntax
setcookie(name, value, expire, path, domain);
Example:
<?php
setcookie("user", "Alex Porter", time()+3600);
?>

Example
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
Example
Pro.php
<?php
setcookie(x,100);
echo $_COOKIE[‘x’];
?>
<a href=”p1.php”>GO</a>
P1.php

Prepared By: Dept Of CSE, RGMCET Page 45


PHP PROGRAMMING

<?php
echo “HI”;
echo $_COOKIE[‘x’];
?>
NOTE:
At the time of 1st execution, the value of x is not shown in the output. Since
the time setcookie() is creating the cookie, the next statement is executed. This
setcookie() takes some time to create cookie, thus we are unable to see value of
x at first execution.

HOW TO VIEW COOKIES IN BROWSER?


Open your Browser  Tools  Privacy  Custom selection for history 
 Show cookie  Cookies folder will be shown
HOW TO RETRIEVE A COOKIE VALUE?
 The PHP $_COOKIE variable is used to retrieve a cookie value.
<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>
In the following example we use the isset() function to find out if a cookie has
been set:
Example:
<html>
<body>
<?php
if (isset($_COOKIE["user"]))

Prepared By: Dept Of CSE, RGMCET Page 46


PHP PROGRAMMING

echo "Welcome " . $_COOKIE["user"] . "!<br />";


else
echo "Welcome guest!<br />";
?>
</body>
</html>

HOW TO DELETE A COOKIE?


When deleting a cookie you should assure that the expiration date is in the
past.
Example:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
HOW TO CREATE PERSISTENCE COOKIES?
There are four steps to create persistence cookies.
1. Find out current date and time information when cookie is downloading
into client system.
2. Add lifetime to current date and time to get expiry time.
3. Create cookie in client system with the resultant expiry time.
<?php
setcookie(“sno”,123,time()+3600);
Current time Expiry(in Sec)
echo $_COOKIE[‘sno’];
?>
4. We can destroy the cookies before its expiry time by recreating the cookie
with completed time.

Prepared By: Dept Of CSE, RGMCET Page 47


PHP PROGRAMMING

<?php
setcookie(“sno”,’ ‘,time()-1);
?>
WHAT IF A BROWSER DOES NOT SUPPORT COOKIES?
 If your application deals with browsers that do not support cookies, you
will have to use other methods to pass information from one page to
another in your application. One method is to pass the data through
forms (forms and user input are described earlier in this tutorial).
 The form below passes the user input to "welcome.php" when the user
clicks on the "Submit" button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

Retrieve the values in the "welcome.php" file like this:

<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>

Prepared By: Dept Of CSE, RGMCET Page 48


PHP PROGRAMMING

LIMITATIONS OF COOKIE:
1. It can store limited amount of data.
2. It can store only text data.
3. Data of cookie is storing in browser memory location, that’s why we
should store secure information in cookies. If you want to store secure
data, we should get user’s permission.
Program: Pro.php
<?php
if(isset($_POST[‘sub’]))
{
$sp=$_POST[‘d1’];
$qty=$_POST[‘tqty’];
setcookie($sp,$qty);
}
?>
<form method=”post” action=” ”>
Select Product:<select name=”d1”>
<option>Samsung</option>
<option>Nokia</option>
<option>Apple</option>
</select><br>
Enter Quantity:<input name=”tqty”>
<br>
<input name=”submit” type=”submit” value=”Add to Cart”>
</form>
<a href=”bill.php”>Bill</a>

Bill.php

Prepared By: Dept Of CSE, RGMCET Page 49


PHP PROGRAMMING

<?php
foreach($_COOKIE as $k$v)
{
echo $k;
echo “=”;
echo $v;
echo “<br>”;
}
?>
8. $_FILES
 By using this, we can get information of uploaded file.
 It is a 2-D array variable that contains 5 elements. Each element is
providing information about uploaded files. Every element’s first
dimension is name of upload control.
BASIC CONCEPTS OF UPLOADING FILE:
 If user uploaded any file from browser to server, first that file transfers to
temporary memory location of server. We need to implement PHP script
to move that file from temporary memory location to permanent memory
location.
 Server will provide unique name at the time of storing file in temporary
memory location.
ELEMENTS OF $_FILES:

A. $_FILES['file']['tmp_name'] – To get temporary filename which is


provided by server.

B. $_FILES['file']['name'] –Holds the actual name of the uploaded file.

C. $_FILES['file']['size'] – Holds the size in bytes of the uploaded file.

Prepared By: Dept Of CSE, RGMCET Page 50


PHP PROGRAMMING

D. $_FILES['file']['type'] – Holds MIME type of uploaded file.

E. $_FILES['file']['error'] − Error occurred at the time of uploading a file.

 To get error number, if any occurred at the time of uploading file.

 If number is 0, there is no error.

 If number is 1, then file size is maximum than server configuration


setting.

 If number is 2, then file size is maximum than browser configuration


setting.

 If number is 3, network problem at the time of uploading a file.

 If number is 4, user select submit button without any file selection.

Example:
<?php
if(isset($_FILES['image']))
{
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false)
{

Prepared By: Dept Of CSE, RGMCET Page 51


PHP PROGRAMMING

$errors[]="extension not allowed, please choose a JPEG or PNG


file.";
}
if($file_size > 2097152) {
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}
else{
print_r($errors);
}
}
?>
<html>
<body>
<form action = "" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "image" />
<input type = "submit"/>
<ul>
<li>Sent file: <?php echo $_FILES['image']['name']; ?>
<li>File size: <?php echo $_FILES['image']['size']; ?>
<li>File type: <?php echo $_FILES['image']['type'] ?>
</ul>
</form>
</body>
</html>

Prepared By: Dept Of CSE, RGMCET Page 52


PHP PROGRAMMING

Output:

MIME:
 It stands for Multipurpose Internet Mailing Extension.
 It is a type of extension used to upload a file from browser to server.
 Every file contains different types of MIME types to upload into server
from browser.
 Available MIME types are:
1. jpg - image/jpeg
2. bmp - image/bmp
3. exe - application/octet-stream
4. pdf - application/pdf
5. multipart/form-data - using this we can upload any type of file
from browser to server.
6. is_uploaded_file - using this function, we can check a file can be
uploaded or not from temporary memory
location to permanent memory location.
7. move_uploaded_file - to move the uploaded file from temporary
memory location to permanent memory location.
Example: select.html
<form method=”POST” enctype=”multipart/form-data” action=”upload.php”>
Select File:<input name=”f1” type=”file”> <br>
<input name=”sub” type=”submit” value=”upload”>

Prepared By: Dept Of CSE, RGMCET Page 53


PHP PROGRAMMING

</form>
Upload.php
<?php>
print_r($_FILES);
$fname=$_FILES[‘f1’][‘name’];
echo $fname;
if(move_uploaded_file($_FILES[‘f1][‘tmp_name’],”up/$fname”))
echo “File is moved”;
else
echo “Not”;
?>
Example: To allow all files except .exe files.
<?php
if($_FILES[‘f1’][type’]==”application/octet_stream”)
{
echo “exe not supported”
}
else
move_uploaded_file($_FILES[‘f1][‘tmp_name’],”up/”.$_FILES[‘f1][‘name’]);
?>
 Without MIME types, we won’t be able to upload file, only txt controls
will be supported.
CONFIGURATION SETTINGS TO WORK WITH FILE UPLOAD CONCEPT:
file_upload
 Using this we can allow and stop file uploads. Default value is ON, by
changing this value as OFF we can stop file uploads.
upload_tmp_dir

Prepared By: Dept Of CSE, RGMCET Page 54


PHP PROGRAMMING

 Using this we can change temporary directory location of uploaded file.


By default, all files will store in tmp folder.
upload_max_filesize
 Using this we can increase or decrease maximum file size to upload the
files(by default 128MB).
PROTOCOLS:
 Protocols are set of instructions to transfer data from one page to
another page.
 Protocols are mainly divided into two types:
1. Stateful protocols:
These protocols can maintain the state of application. i.e. they can
remember previous pages data in current pages. In windows application, we
are using these protocols.
E.g., TCP/IP, FTP etc.
2. Stateless protocols:
These protocols cannot maintain state of application. In web application, we
are using these protocols because they don’t carry previous data into
current page, that’s why performance is very fast.
E.g., HTTP, HTTPS
9. $_ENV
 $_ENV global variable in PHP is a predefined reserved variable that
contains an array of information related to the environment in which
PHP script is running.
Example:
<?php
echo 'My username is ' .$_ENV["USER"] . '!';
?>
 By using this function, we can get all configuration settings.

Prepared By: Dept Of CSE, RGMCET Page 55


PHP PROGRAMMING

<?php
phpinfo();
?>

VALIDATING FORM INPUT


Required field will check whether the field is filled or not in the proper way.
Most of cases we will use the * symbol for required field.
What is Validation?
Validation means check the input submitted by the user. There are two types
of validation are available in PHP. They are as follows −
1. Client-Side Validation − Validation is performed on the client machine
web browsers.
2. Server Side Validation − After submitted by data, the data has sent to a
server and perform validation checks in server machine.

Prepared By: Dept Of CSE, RGMCET Page 56


PHP PROGRAMMING

<html>
<body>
<?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{
$nameErr = "Name is required";
}
else
{
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
Prepared By: Dept Of CSE, RGMCET Page 57
PHP PROGRAMMING

}
else
{
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"]))
{
$website = "";
}
else
{
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"]))
{
$comment = "";
}
else
{
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"]))
{
$genderErr = "Gender is required";
}
else
{
$gender = test_input($_POST["gender"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

Prepared By: Dept Of CSE, RGMCET Page 58


PHP PROGRAMMING

<h2>Absolute classes registration</h2>


<p><span class = "error">* required field.</span></p>
<form method = "post"
action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?
>">
<table>
<tr>
<td>Name:</td>
<td><input type = "text" name = "name">
<span class = "error">* <?php echo $nameErr;?
></span>
</td>
</tr>
<tr>
<td>E-mail: </td>
<td><input type = "text" name = "email">
<span class = "error">* <?php echo $emailErr;?
></span>
</td>
</tr>
<tr>
<td>Time:</td>
<td> <input type = "text" name = "website">
<span class = "error"><?php echo $websiteErr;?></span>
</td>
</tr>
<tr>
<td>Classes:</td>
<td> <textarea name = "comment" rows = "5" cols =
"40"></textarea></td>
</tr>
<tr>
<td>Gender:</td>
<td>
<input type = "radio" name = "gender" value =
"female">Female
<input type = "radio" name = "gender" value =
"male">Male
<span class = "error">* <?php echo $genderErr;?
></span>
</td>
</tr>

Prepared By: Dept Of CSE, RGMCET Page 59


PHP PROGRAMMING

<td>
<input type = "submit" name = "submit" value = "Submit">
</td>
</table>
</form>
<?php
echo "<h2>Your given values are as:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>

die(): It is an inbuilt function in PHP. It is used to print message and exit from
the current php script. It is equivalent to exit() function in PHP.
<?php
$site = "";
fopen($site, "r")
or die("Unable to connect to given site.");
?>
Output: Unable to connect to given site.
CONSTRAINTS IN MYSQL
 MySQL CONSTRAINT is used to define rules to allow or restrict what
values can be stored in columns. The purpose of inducing constraints is
to enforce the integrity of a database.
 MySQL CONSTRAINTS are used to limit the type of data that can be
inserted into a table.
 MySQL CONSTRAINTS can be classified into two types - column level
and table level.

Prepared By: Dept Of CSE, RGMCET Page 60


PHP PROGRAMMING

 The column level constraints can apply only to one column whereas table
level constraints are applied to the entire table.
 MySQL CONSTRAINT is declared at the time of creating a table.
 Constrains are used to apply some conditions on tables. MySQL is
supporting different types of constraints.
1. NOT NULL
MySQL NOT NULL constraint allows to specify that a column can not contain
any NULL value. MySQL NOT NULL can be used to CREATE and ALTER a
table.
Example:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT
NULL,FirstName varchar(255) NOT NULL, Age int );
2. UNIQUE
The UNIQUE constraint in MySQL does not allow to insert a duplicate value in
a column. The UNIQUE constraint maintains the uniqueness of a column in a
table. More than one UNIQUE column can be used in a table.
Example:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT
NULL,FirstName varchar(255), Age int, UNIQUE (ID) );
3. PRIMARY KEY
A PRIMARY KEY constraint for a table enforces the table to accept unique data
for a specific column and this constraint creates a unique index for accessing
the table faster.
Example:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT
NULL,FirstName varchar(255), Age int, PRIMARY KEY (ID) );
4. AUTO_INCREMENT

Prepared By: Dept Of CSE, RGMCET Page 61


PHP PROGRAMMING

AUTO_INCREMENT allows a unique number to be generated automatically


when a new record is inserted into a table. Often this is the primary key field
that we would like to be created automatically every time a new record is
inserted.
Example:
CREATE TABLE Persons ( ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL, FirstName
varchar(255),Age int, PRIMARY KEY (ID) );
5. DEFALUT
The DEFAULT constraint is used to provide a default value for a column. The
default value will be added to all new records IF no other value is specified.
Example:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT
NULL,
FirstName varchar(255), Age int,
City varchar(255) DEFAULT 'Sandnes' );
6. FOREIGN KEY
A FOREIGN KEY in MySQL creates a link between two tables by one specific
column of both tables. The specified column in one table must be a PRIMARY
KEY and referred by the column of another table known as FOREIGN KEY.
Example:
CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT
NULL,
PersonID int, PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES
Persons(PersonID) );
7. CHECK

Prepared By: Dept Of CSE, RGMCET Page 62


PHP PROGRAMMING

A CHECK constraint controls the values in the associated column. The CHECK
constraint determines whether the value is valid or not from a logical
expression.
Example:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT
NULL,FirstName varchar(255), Age int, CHECK (Age>=18) );

mysqli_select_db(): To is used to select the particular database from mysql.


This function returns TRUE on success, or FALSE on failure
Syntax: mysqli_select_db(connection,dbname);
mysqli_query(): To execute an SQL query against the database. On success it
returns TRUE. FALSE on failure
Syntax: mysqli_query(connection,query);
mysqli_error():The mysqli_error() function returns the last error description for
the most recent function call, if any. It returns a string that describes the error.
An empty string if no error occurred.
Syntax: mysqli_error(connection);
mysqli_connect_error(): This function returns the error description from the
last connection error, if any. Returns a string that describes the error. NULL if
no error occurred
Syntax: mysqli_connect_error();
mysql_fetch_row():The mysql_fetch_row() function returns a row from a recordset as a numeric
array. This function gets a row from the mysql_query() function and returns an array on success, or
FALSE on failure or when there are no more rows.
mysql_fetch_row(data)

mysql_fetch_assoc():

Prepared By: Dept Of CSE, RGMCET Page 63


PHP PROGRAMMING

This function fetches the record from result set and it returns output as an
associative array. Key is a column names, values are column values.
mysql_fetch_array():The mysql_fetch_array() function returns a row from a recordset as an
associative array and/or a numeric array. This function gets a row from the mysql_query () function and
returns an array on success, or FALSE on failure or when there are no more rows .It is combination
of previous two functions reads a record from result set and returns output as
an associative array, a numeric array, or both
mysql_fetch_object():
It reads a record from result set and returns output as an object. Object is a
collection of properties. Property names are column names and values are
column values. This object belongs to stdclass.
mysql_num_fields():The To get total number of fields from result set.
mysql_fetch_field():mysql_fetch_field() function returns an object containing
information of a field from a recordset. This function gets field data from the
mysql_query() function and returns an object on success, or FALSE on failure
or when there are no more rows.
To fetch complete information of a field and returns output as an object.
mysql_fetch_field($result)

mysql_field_type():
To get the type of field from the result set.
mysql_field_name():The mysql_field_name() function returns the name of a field in a recordset.
Returns the field name on success, or FALSE on failure.
To get the name of field from result set.
mysql_field_name(data,field_offset)

mysql_field_len():
To get the length of the field from result set.

Prepared By: Dept Of CSE, RGMCET Page 64


PHP PROGRAMMING

mysql_get_client_info():
To get version information of mysql database.
mysql_data_seek():
To locate result set pointer on specified record.
mysql_field_seek():
To locate result set pointer on specified column.
mysql_close():
To close the opened mysql connections.
mysql_list_dbs():
To get list of databases available.
mysql_list_tables():
To get the list of tables available in a database.
https://www.studentstutorial.com/php/php-update-multiple-row.php

Prepared By: Dept Of CSE, RGMCET Page 65

You might also like