PHP and Web Forms
PHP and Web Forms
PHP and Web Forms, Sending Form Data to a Server, Working with Cookies and
Session Handlers, PHP with MySQL - Interacting with the Database, Prepared
Statement, Database Transactions.
How PHP is able to accept and process data submitted through a web form.
Web Forms are used to encourage:
Registration site
facilitate forum conversations
collect mailing and billing addresses for online orders, and much more.
Coding HTML form: only part of what’s required to effectively accept user input.
There are two ways the browser client can send information to the web server.
Note that the query string (name/value pairs) is sent in the URL of a GET request:
The GET method sends the encoded user information appended to the page request.
GET Method
The page and the encoded information are separated by the ? character.
Example: http://www.test.com/index.htm?name1=value1&name2=value2
UNIT-IV 1 SVEC-Autonomous
III- ‘B’ Web Programming
Important Concepts of GET Request:
Once this form is submitted, you can reference that text-field value like so:
$_GET['email']
for sake of convenience, nothing prevents you from first assigning this value to another
Variable
$email = $_GET['email'];
Note: The Query string (name/value pairs) is sent in the HTTP message body of a POST
request.
The POST method transfers information via HTTP headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING.
UNIT-IV 2 SVEC-Autonomous
III- ‘B’ Web Programming
POST-Example:
Suppose the form contains a text-field value named email.
<input type="text" id="email" name="email" size="20" maxlength="40" />
Once this form is submitted, you can reference that text-field value like so:
$_POST['email']
for sake of convenience, nothing prevents you from first assigning this value to another
Variable
$email = $_POST['email'];
******************************************************************************
Example: Displays a simple HTML form with two input fields and a submit button:
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
OUTPUT:
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. The "welcome.php"
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
UNIT-IV 3 SVEC-Autonomous
III- ‘B’ Web Programming
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
Output:
Welcome III-B
Your email address is csetitans.com
<?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"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
UNIT-IV 4 SVEC-Autonomous
III- ‘B’ Web Programming
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the
URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
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;
}
?>
UNIT-IV 5 SVEC-Autonomous
III- ‘B’ Web Programming
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
OUTPUT:
UNIT-IV 6 SVEC-Autonomous
III- ‘B’ Web Programming
// Working with COOKIES
What is a Cookies?
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.
Cookies are text files stored on the client computer and they are kept of use tracking
purpose
Operations in PHP-Cookies
1.) Create Cookies with PHP
2.) Accessing/Retrieve Cookies with PHP
3.) Modify Cookie value
4.) Check Cookies is set or not
5.) Check if Cookies are Enabled
6.) Deleting Cookie with PHP
1.) Create Cookies With PHP:
A cookie is created with the setcookie() function.
Syntax:
NOTE: Only the name parameter is required.All other parameters are optional.
name and age these cookies will be expired after one hour.
<?php
setcookie("name", "John Watkin", time()+(86400 * 30), "/","", 0);
setcookie("age", “36", time()+(86400 * 30), "/", "", 0);
?>
<html> <head>
<title>Setting Cookies with PHP</title> </head> <body>
<?php echo "Set Cookies“
?> </body> </html>
UNIT-IV 7 SVEC-Autonomous
III- ‘B’ Web Programming
Explanation:
<html> <head>
<title>Accessing Cookies with PHP</title> </head> <body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["age"] . "<br />";
?> </body> </html>
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
UNIT-IV 8 SVEC-Autonomous
III- ‘B’ Web Programming
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
<p><strong>Note:</strong> You might have to reload the page to see the new value of the
cookie.</p>
</body>
</html>
OUTPUT:
Cookie named 'user' is not set!
Note: You might have to reload the page to see the new value of the cookie.
<html> <head>
<title>Accessing Cookies with PHP</title> </head> <body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?> </body> </html>
<!DOCTYPE html>
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
UNIT-IV 9 SVEC-Autonomous
III- ‘B’ Web Programming
</body>
</html>
OUTPUT:
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html> <head>
<title>Deleting Cookies with PHP</title>
</head> <body>
<?php
echo "Deleted Cookies “
?>
</body> </html>
Getting Cookie
=============================
<?php
echo $_COOKIE["your cookie name"];
?>
UNIT-IV 10 SVEC-Autonomous
III- ‘B’ Web Programming
Updating Cookie
=============================
<?php
setcookie("color","red");
echo $_COOKIE["color"];
/*color is red*/
/* your codes and functions*/
setcookie("color","blue");
echo $_COOKIE["color"];
/*new color is blue*/
?>
Deleting Cookie
==============================
<?php
unset($_COOKIE["yourcookie"]);
/*Or*/
setcookie("yourcookie","yourvalue",time()-
1);
/*it expired so it's deleted*/
?>
Advantages of COOKIES:
1. Cookies don not require any server resources since they are stored on the client.
2. Cookies are easy to implement.
3. You can configure cookies to expire when the browser session ends(session cookies) or they
can exist for a specified length of time on the client computer(persistent cookies)
Disadvantages of COOKIES:
````````````````````````````````````````````````````````````````````````````````````````````````````````````````````
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
The location of the temporary file is determined by a setting in the php.ini file called
session.save_path.
UNIT-IV 11 SVEC-Autonomous
III- ‘B’ Web Programming
- PHP first creates a unique identifier for that particular session which is a random string
of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
- A cookie called PHPSESSID is automatically sent to the user's computer to store unique
session identification string.
- A file is automatically created on the server in the designated temporary directory and
bears the name of the unique identifier prefixed by
sess_ ie sess_3c7foj34c3jj973hj kop2fc937e3443.
** What is Session ID?
• (SID), and then correlating that SID with any number of other pieces of data, be it
number of monthly visits, favorite background color, or middle name—you name it.
Session variables are set with the PHP global variable: $_SESSION.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html> <body>
UNIT-IV 12 SVEC-Autonomous
III- ‘B’ Web Programming
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body> </html>
<?php
session_start();
?>
<!DOCTYPE html>
<html> <body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body> </html>
<?php
session_start();
?>
<!DOCTYPE html>
<html> <body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
echo "All session variables are now removed, and the session is destroyed."
?>
</body> </html>
UNIT-IV 13 SVEC-Autonomous
III- ‘B’ Web Programming
// PHP AND MYSQL- INTERACTING WITH DATABASE
**Why MYSQL for PHP?
MYSQL - BASICS:
updated MySQL extension with PHP 5, known as (MySQL Improved) (and typically
referred to as mysqli)
2. native object-oriented interface that would not only more tightly integrate with other
Applications.
Object oriented:
A series of classes, more convenient and efficient programming paradigm.
Prepared Statements:
Eliminate overhead and Inconvenience when working with queries another important
security-related feature in that they prevent SQL injection attacks.
Transactional Support:
Although MySQL’s transactional capabilities are available the mysqli extension offers
an object-oriented interface to these capabilities
Enhanced debugging capabilities:
The mysqli extension offers numerous methods for debugging queries, resulting in a
more efficient development process.
Embedded server support:
The mysqli extension offers methods for connecting and manipulating these embedded
MySQL databases.
UNIT-IV 14 SVEC-Autonomous
III- ‘B’ Web Programming
// Interacting With Database
The vast majority of your queries will revolve around creation, retrieval, update, and
deletion tasks, collectively known as CRUD.
The method query() is responsible for sending the query to the database.
Example:
class mysqli {
mixed query(string query [, int resultmode])
}
resultmode parameter is used to modify the behavior of this method, accepting two
Values:
i.) MYSQLI_STORE_RESULT:
Returns the result as a buffered set, meaning the entire set will be made available for
navigation at once.
ii.) MYSQLI_USE_RESULT:
Returns the result as an unbuffered set, meaning the set will be retrieved on an as-needed
basis from the server.
Unbuffered result sets increase performance for large result sets,
Retrieving Data:
The following example retrieves the sku, name, and price columns from the products table,
ordering the results by name.
<?php
$mysqli = new mysqli('localhost', 'catalog_user', 'secret', 'corporate');
// Create the query
$query = 'SELECT sku, name, price FROM products ORDER by name';
// Send the query to MySQL
$result = $mysqli->query($query, MYSQLI_STORE_RESULT);
// Iterate through the result set
while(list($sku, $name, $price) = $result->fetch_row())
printf("(%s) %s: \$%s <br />", $sku, $name, $price);
?>
UNIT-IV 15 SVEC-Autonomous
III- ‘B’ Web Programming
Output
(TY232278) AquaSmooth Toothpaste: $2.25
(PO988932) HeadsFree Shampoo: $3.99
(ZP457321) Painless Aftershave: $4.50
(KL334899) WhiskerWrecker Razors: $4.17
Deleting Data
<?php
$mysqli = new mysqli('localhost', 'catalog_user', 'secret', 'corporate');
// Create the query
$query = "DELETE FROM products WHERE sku = 'TY232278'";
// Send the query to MySQL
$result = $mysqli->query($query, MYSQLI_STORE_RESULT);
// Tell the user how many rows have been affected
printf("%d rows have been deleted.", $mysqli >affected_rows);
?>
<html>
<head>
<title>Database and table creation</title>
</head>
UNIT-IV 16 SVEC-Autonomous
III- ‘B’ Web Programming
<body>
<form method="post" action="createdb.php">
Username<input type="text" name="uname"><br>
password<input type="password" name="pass"><br>
<input type="submit" name="register" value="register">
</form>
</body>
</html>
<?php
if(isset($_POST['register'])){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
UNIT-IV 17 SVEC-Autonomous
III- ‘B’ Web Programming
$conn->close();
}
else{
header("location:register.php");
}
?>
// PREPARED STATEMENTS
** Why Prepared Statements?
Some looping mechanism in query comes at a cost, because of the repeated parsing of the
almost identical query for validity, and coding convenience, because of the need to repeatedly
reconfigure the query using the new values for each iteration.
To help resolve the issues incurred by repeatedly executed queries, MySQL 4.1 introduced
prepared statements, which can accomplish the tasks described above at a significantly lower
cost of overhead, and with fewer lines of code.
Two variants of prepared statements are available:
1.) Bound parameters: The bound-parameter variant allows you to store a query on
the MySQL server, with only the changing data being repeatedly sent to the server and
integrated into the query for execution.
For instance, suppose you create a web application that allows users to manage store
products. To jumpstart the initial process, you might create a web form that accepts up to 20
product names, IDs, prices, and descriptions. Because this information would be inserted using
identical queries (except for the data, of course), it makes sense to use a boundparameter
prepared statement.
2.) Bound results: The bound-result variant allows you to use sometimes unwieldy
Indexed or Associative arrays to pull values from result sets by binding PHP variables to
corresponding retrieved fields, and then using those variables as necessary.
For instance, you might bind the URL field from a SELECT statement retrieving product
information to variables named $sku, $name, $price, and $description.
class mysqli_stmt {
boolean prepare(string query)
}
EXAMPLE:
<?php
// Create a new server connection
UNIT-IV 18 SVEC-Autonomous
III- ‘B’ Web Programming
$mysqli = new mysqli('localhost', 'catalog_user', 'secret', 'corporate');
// Create the query and corresponding placeholders
$query = "SELECT sku, name, price, description FROM products ORDER BY sku";
// Create a statement object
$stmt = $mysqli->stmt_init();
// Prepare the statement for execution
$stmt->prepare($query);
.. Do something with the prepared statement
// Recuperate the statement resources
$stmt->close();
// Close the connection
$mysqli->close();
?>
class stmt {
boolean execute()
}
class stmt {
boolean close()
}
class stmt {
boolean bind_param(string types, mixed &var1 [, mixed &varN])
}
UNIT-IV 19 SVEC-Autonomous
III- ‘B’ Web Programming
EXAMPLE:
Binding Parameters with the mysqli Extension
<?php
// Create a new server connection
$mysqli = new mysqli('localhost', 'catalog_user', 'secret', 'corporate');
// Create the query and corresponding placeholders
$query = "INSERT INTO products SET id=NULL, sku=?,
name=?, price=?";
// Create a statement object
$stmt = $mysqli->stmt_init();
// Prepare the statement for execution
$stmt->prepare($query);
// Bind the parameters
$stmt->bind_param('ssd', $sku, $name, $price);
// Assign the posted sku array
$skuarray = $_POST['sku'];
// Assign the posted name array
$namearray = $_POST['name'];
// Assign the posted price array
$pricearray = $_POST['price'];
// Initialize the counter
$x = 0;
// Cycle through the array, and iteratively execute the query
while ($x < sizeof($skuarray)) {
$sku = $skuarray[$x];
$name = $namearray[$x];
$price = $pricearray[$x];
$stmt->execute();
}
// Recuperate the statement resources
$stmt->close();
// Close the connection
$mysqli->close();
?>
class mysqli {
boolean fetch()
}
UNIT-IV 20 SVEC-Autonomous
III- ‘B’ Web Programming
// Database Transactions
Three new methods enhance PHP’s ability to execute MySQL transactions. the three
relevant methods concerned with committing and rolling back a transaction are introduced for
purposes of reference.
class mysqli {
boolean autocommit(boolean mode)
}
Passing a value of TRUE via mode enables autocommit, while FALSE disables it, in either
case returning TRUE on success and FALSE otherwise.
2. Committing a Transaction:
The commit() method commits the present transaction to the database, returning TRUE
on success and FALSE otherwise. Its prototype follows:
class mysqli {
boolean commit()
}
class mysqli {
boolean rollback()
}
UNIT-IV 21 SVEC-Autonomous