PHP Programming Unit 6
PHP Programming Unit 6
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.
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
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:
<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.
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
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.
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 = "";
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);
$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;
?>
</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>
</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.
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.
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,
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
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.
if (!$conn)
die("Connection failed: " . mysqli_connect_error());
echo "Connected successfully";
?>
Or
<?php
$con=mysql_connect(localhost”,”root”,””);
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());
$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());
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
{
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>";
}
}
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
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);
?>
$_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
The following table lists the most important elements that can go inside
$_SERVER:
Element/Code Description
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
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.
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();
?>
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
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
<?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.
<?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>
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
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
<?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:
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)
{
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”>
</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
<?php
phpinfo();
?>
<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;
}
?>
<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.
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
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) );
mysql_fetch_assoc():
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.
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