0% found this document useful (0 votes)
24 views89 pages

Module 4 Ref

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

Module 4 Ref

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

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

CST463 - WEB PROGRAMMING

Page 1
CST463 - WEB PROGRAMMING

Page 2
Module 4 (CO3, Cognitive Knowledge Level: Apply)

► Form processing and Business Logic


► Cookies- Sessions
► MySQL Integration-Connecting to MySQL with PHP
► Performing CREATE, DELETE, INSERT, SELECT and UPDATE operations
on MySQL table
► Working with MySQL data
► Reading from Database-Dynamic Content.

Page 3
Form processing and Business Logic

Page 4
Form processing
► Superglobal arrays are associative arrays predefined by PHP that hold variables
acquired from user input, the environment or the web server, and are accessible in
any variable scope. Some of PHP’s superglobal arrays

► The arrays $_GET and $_POST retrieve information sent to the server by HTTP get
and post requests, respectively, making it possible for a script to have access to
this data when it loads another page
Page 5
Form processing
► when PHP is used for form handling, the PHP script is embedded in an XHTML
document, like other uses of PHP.
► The recommended approach is to use the implicit arrays for form values, $_POST
and $_GET.
► These arrays have keys that match the form element names and values that were
input by the client.
► For example, if a form has a text box named phone and the form method is POST,
the value of that element is available in the PHP script as follows:
$_POST["phone"]
►The built-in $_GET function is used to collect values from a form sent with
method="get".
►Information sent from a form with the GET method is visible to everyone and has
limits on the amount of information to send (max. 100 characters).
Page 6
Form processing $_POST Function

Page 7
Form processing $_GET Function

Page 8
Form processing

Page 9
Form processing

Page 10
Simple PHP Program to generate a simple calculator
► To find basic mathematical operations on two numbers

Page 11
Simple PHP Program to generate a simple calculator
► To find basic mathematical operations on two numbers

Page 12
Simple PHP Program to generate a simple calculator
► To find basic mathematical operations on two numbers

Page 13
Modified PHP Program to generate a simple calculator
► To find basic mathematical operations on two numbers

Page 14
Modified PHP Program to generate a simple calculator

Page 15
Modified PHP Program to generate a simple calculator

Page 16
Cookies and Session

Page 17
Cookies
► 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.
► Cookies provide a general approach to storing information about sessions on
the browser system itself.
► The server is given this information when the browser makes subsequent
requests for Web resources from the server.
► Cookies allow the server to present a customized interface to the client.
► They also allow the server to connect requests from a particular client to
previous requests, thereby connecting sequences of requests into a session.

Page 18
Cookies
► A cookie is a small object of information that consists of a name and a textual
value.
► A cookie is created by some software system on the server.
► A message from a browser to a server is a request; a message from a server to a
browser is a response. The header part of an HTTP communication can include
cookies. So, every request sent from a browser to a server, and every response
from a server to a browser, can include one or more cookies.
► At the time it is created, a cookie is assigned a lifetime. When the time a cookie
has existed reaches its associated lifetime, the cookie is deleted from the
browser's host machine.
► a particular cookie is information that is exchanged exclusively between one
specific browser and one specific server.

Page 19
Cookies- setcookie function
► A cookie is set in PHP with the setcookie function. This function takes one or
more parameters.
setcookie(name, value, expire, path)
► The first parameter, which is mandatory, is the cookie's name given as a string.
The second, if present, is the new value for the cookie, also a string. If the value
is absent, setcookie undefines the cookie. The third parameter, when present, is
the expiration time in seconds for the cookie, given as an integer.
► The default value for the expiration time is zero, which specifies that the cookie
is destroyed at the end of the current session
setcookie(“valid", "true", time() + 86400);
► This call creates a cookie named "valid" whose value is "true" and whose
lifetime is one day (86,400 is the number of seconds in a day).

Page 20
Cookies- setcookie function

Page 21
Cookies- setcookie-delete function
► The example creates a cookie named "user" with the value “admin123".
► The cookie will expire after 30 days (86400 * 30).
► The "/" means that the cookie is available in entire website (otherwise, select
the directory you prefer).
► retrieve the value of the cookie "user" (using the global variable $_COOKIE).
► use the isset() function to find out if the cookie is set:
► To delete a cookie, use setcookie() function with an expiration date in the past:
► Example

Page 22
Cookies- setcookie function
► In PHP, cookie values are treated much like form values.
► All cookies that arrive with a request are placed in the implicit $_COOKIES
array, which has the cookie names as keys and the cookie values as values.
► most browsers have a limit on the number of cookies that will be accepted from
a particular server site.
► In many cases, information about a session is needed only during the session
► Rather than using one or more cookies, a single session array can be used to
store information about the previous requests of a client during a session.
► In particular, session arrays often store a unique session ID for a session.

Page 23
Cookies- setcookie function

Page 24
Cookies- setcookie function

Page 25
Cookies- setcookie function

Page 26
Session
► When you work 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 the web server does not know who you are or what you do,
because the HTTP address doesn't maintain state.
► Session variables solve this problem by storing user information to be used
across multiple pages (e.g. username ,pwd etc). By default, session variables last
until the user closes the browser.
► So; Session variables hold information about one single user, and are available
to all pages in one application.

Page 27
Session
► One significant way that session arrays differ from cookies is that they can be
stored on the server, whereas cookies are stored on the client.
► In PHP, a session ID is an internal value that identifies a session.
► Session IDs need not be known or handled in any way by PHP scripts.
► PHP is made aware that a script is interested in session tracking by calling the
session_start function, which takes no parameters. The first call to session_start
in a session causes a session ID to be created and recorded.
► On subsequent calls to session_start in the same session, the function retrieves
the $_SESSION array, which stores any session variables and their values that
were registered in previously executed scripts in this session.
► A session is started with the session_start() function.
► Session variables are set with the PHP global variable: $_SESSION

Page 28
Set Session variables

Page 29
Modify Session variables

Page 30
Destroy a Session
► To remove all global session variables and destroy the session, use
session_unset() and session_destroy():
► Example

Page 31
MySQL Integration-Connecting to MySQL with PHP

Page 32
Connecting PHP to MySQL

► When users enter any data into the fields of your forms, you need to collect
that information and add it to the database.To do that, you want to know how
to connect PHP with MySQL.
► In order to connect a MySQL database to PHP, you require MySQL on your
computer, a tool to create and manage databases, and PHP installed. The most
popular ways to connect a PHP script to MySQL are MySQli and PDO

Page 33
Connecting PHP to MySQL
► What is MySQL?
► MySQL is an open-source relational database management system (RDBMS). It is the
most popular database system used with PHP.
► Structured Query Language (SQL). The data in a MySQL database are stored in tables
that consist 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 a very fast, reliable, and easy-to-use database system. It
uses standard SQL. MySQL compiles on a number of platforms.
► How we can connect PHP to MySQL?
► PHP 5 and later can work with a MySQL database using:
► MySQLi extension (the ‘i’ is abbreviation for improved)
► PDO (PHP Data Objects)

Page 34
Connecting PHP to MySQL
► Connection to MySQL using MySQLi
► PHP provides mysql_connect() function to open a database connection.
► This function takes a single parameter, which is a connection returned by the
mysql_connect() function.
► You can disconnect from the MySQL database anytime using another PHP
function mysql_close().
► There is also a procedural approach of MySQLi to establish a connection to
MySQL database from a PHP script.

Page 35
Form processing with DB- Making a Connection
► The basic syntax for a connection to MySQL is as follows:

$mysqli = mysqli_connect("hostname", "username", "password", "database");


► The value of $mysqli is the result of the function and is used in later functions for
communicating with MySQL.
► With sample values inserted, the connection code looks like this:

$mysqli = mysqli_connect("localhost", “root", “ ", "test");


► It creates a new connection in line 2 and then tests to see whether an
error occurred. If an error occurred, an error message and uses the
mysqli_connect_error() function to print the message.

Page 36
Form processing with DB- Making a Connection

Page 37
Form processing with DB- Making a Connection with ‘test’ DB

► MySQL_i_Connect_error

Page 38 Prof.Smitha Jacob, Department of Computer Science and Engineering, SJCET Palai
Form processing with DB- Making a Connection
► The basic syntax for a connection to MySQL is as follows:

$mysqli = mysqli_connect("hostname", "username", "password", "database");


► The value of $mysqli is the result of the function and is used in later functions for
communicating with MySQL.
► With sample values inserted, the connection code looks like this:

$mysqli = mysqli_connect("localhost", “root", “ ", "test");


► It creates a new connection in line 2 and then tests to see whether an
error occurred. If an error occurred, an error message and uses the
mysqli_connect_error() function to print the message.

Page 39
Form processing with DB-Executing Queries-Insert records
► PHP to MySQL connection is required to inserts information into our
database.
► Also we should use INSERT INTO … VALUES syntax for that:

Page 40
Form processing with DB-Executing Queries-Insert records
► PHP to MySQL connection is required to inserts information into our
database.
► Also we should use INSERT INTO … VALUES syntax for that:

Page 41
Form processing-Registration form

Page 42
Form processing with DB- Executing Queries
► The mysqli_ query() function in PHP is used to send your SQL query to MySQL
► the mysqli_error() function returns a helpful error message when you make a
mistake
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "INSERT INTO ttest(name,address,gender) VALUES ('$_POST[name]',
'$_POST[address]', '$_POST[gender]')";
if ($conn->query($sql) === TRUE)
{
echo "Data Inserted successfully!";
}

Page 43
Form processing-Registration form

Page 44
Form processing-Registration form

Page 45
Form processing with DB- Creating Tables

Page 46
Form processing with DB- Creating Tables

Page 47
Form processing with DB- Creating Tables

Page 48
Page 49
Form processing with DB- Inserting Tables

Page 50
Form processing with DB- Inserting Tables

Page 51
Select Data From a MySQL Database
► The SELECT statement is used to select data from one or more tables:
SELECT column_name(s) FROM table_name
► or we can use the * character to select ALL columns from a table:
SELECT * FROM table_name
► Select Data With MySQLi can also be done in two ways
► MySQLi Object-oriented
► MySQLi Procedural

Page 52
Select Data From a MySQL Database-MySQLi Object-oriented

Page 53 Prof.Smitha Jacob, Department of Computer Science and Engineering, SJCET Palai
Select Data From a MySQL Database
► First, we set up an SQL query that selects the id, testField columns from the
testTable. The next line of code runs the query and puts the resulting data into a
variable called $result.
► Then, the function num_rows() checks if there are more than zero rows returned.
► If there are more than zero rows returned, the function fetch_assoc() puts all the
results into an associative array that we can loop through. The while() loop loops
through the result set and outputs the data from the id, testField columns.

Page 54
Select Data From a MySQL Database-MySQLi Procedural

Page 55
Update Data In a MySQL Table Using MySQLi
► The UPDATE statement is used to update existing records in a table:
UPDATE table_name SET column1=value, column2=value2,...
WHERE some_column=some_value
► The WHERE clause specifies which record or records that should be updated. If
you omit the WHERE clause, all records will be updated!

Page 56
Update Data In a MySQL Table Using MySQLi-ObjectOriented

Page 57
Update Data In a MySQL Table Using MySQLi contd….

Page 58
Update Data In a MySQL Table Using MySQLi-procedural
contd….

Page 59
Update Data In a MySQL Table Using MySQLi-Procedural

Page 60
Update Data In a MySQL Table Using MySQLi-procedural
contd….

Page 61
Working with sql Data

Page 62
Working with Mysql Data

WARNING
► There is no more support for mysql_* functions,
they are officially deprecated, no longer
maintained and will be removed in the future.
► You should update your code with PDO or
MySQLi to ensure the functionality of your
project in the future

Page 63
Working with Mysql Data

Page 64
Working with Mysql Data

Page 65
Working with Mysql Data

Page 66
Reading from Database Dynamically

Page 67
Accessing Mysql Data-through dynamic Form data

Page 68
Working with Mysql Data-through Form data

Page 69
Working with Mysql Data-through Form data

Page 70
Dynamic Contents

Page 71
Dynamic Content
► PHP can dynamically change the HTML5 it outputs based on a user’s input.
► We can combine the HTML5 form & PHP script into one dynamic document.
► The form is created using a series of loops, arrays and conditionals.
► We add error checking to each of the text input fields and inform the user of
invalid entries on the form itself, rather than on an error page.
► If an error exists, the script maintains the previously submitted values in each
form element.
► Finally, after the form has been successfully completed, we store the input from
the user in a MySQL database.

Page 72
Dynamic Content-Creation of mailinglist Table

Page 73
Page 74
Page 75
Dynamic Content-Variables & Arrays
► Lines 18–24 create variables that are used throughout the script to fill in form
fields and check for errors.
► Line 25 creates an array for formerrors
► Lines 27,29,30 create three arrays, $booklist, $systemlist and $inputlist, that are
used to dynamically create the form’s input fields.

Page 76
Dynamic Content-Variables & Arrays

Page 77
Dynamic Content-Variables & Arrays

Page 78
Dynamic Content-Variables & Arrays
► We specify that the form created in this document is self-submitting (i.e., it posts
to itself) by setting the action to the script 'dynamicForm.php' in line 94.
► Lines 32-72 use the isset function to determine whether the $_POST array
contains keys representing the various form fields.
► These keys exist only after the form is submitted.
► If function isset returns true, then the form has been submitted and we assign the
value for each key to a variable. Otherwise, we assign the empty string to each
variable.
► Line 53 determines whether any errors were detected, while Dynamically Creating
the Form
► If $iserror is false (i.e., there were no input errors), lines 54–88 display the page
indicating that the form was submitted successfully

Page 79
Dynamic Content- Dynamically Creating the Form
► If $iserror is true, lines 54–88 are skipped,
and the code from lines 92-128 executes.
► These lines include a series of print
statements and conditionals to output the
form, as seen in Fig.

Page 80
Page 81
Page 82
Dynamically Creating the Form
► Lines 96–102 iterate through each element in the $inputlist array.
► In line 98 the value of $$inputname is assigned to the text field’s value attribute.
If the form has not yet been submitted, this will be the empty string "".
► The notation $$variable specifies a variable ‘variable’ , which allows the code to
reference variables dynamically.
► You can use this expression to obtain the value of the variable whose name is
equal to the value of $variable.
► PHP first determines the value of $variable, then appends this value to the
leading $ to form the identifier of the variable you wish to reference dynamically.

Page 83
Dynamically Creating the Form
► we use $$inputname to reference the value of each form-field variable.
► During the iteration of the loop, $inputname contains the name of one of the text
input elements, such as "email".
► PHP replaces $inputname in the expression $$inputname with the string
representing that element’s name forming the expression ${"email"}.
► The entire expression then evaluates to the value of the variable $email. Thus, the
variable $email, which stores the value of the e-mail text field after the form has
been submitted, is dynamically referenced.
► This dynamic variable reference is added to the string as the value of the input
field (using the concatenation operator) to maintain data over multiple
submissions of the form.

Page 84
Dynamic Content- Dynamically Creating the Form
► Lines 99-101 add a red asterisk next to the text input fields that were filled out
incorrectly.
► Lines 103-104 display the phone number format instructions in red if the user
entered an invalid phone number.
► Lines 105-112 and 113-125 generate options for the book drop-down list and
operating-system radio buttons, respectively.
► Lines 120–123 select an operating system radio button under two conditions. If
the form is begin displayed for the first time, the first radio button is selected.
Otherwise, if the $currsystem variable’s value matches what’s stored in the $os
variable, that specific radio button is selected

Page 85
Dynamic Content- Inserting Data into the Database

► If the form has been filled out


correctly, lines 56-71 place the
form information in the MySQL
database MailingList using an
INSERT statement.
► Lines 81 generate the web
page indicating a successful
form submission, which also
provides a link to
formDatabase.php (Fig.).

Page 86
Page 87
► Full program
Page 88
Thank You

Page 89

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy