0% found this document useful (0 votes)
6 views40 pages

PHP Part 3 - PHP and MySql

This document discusses how to handle HTML forms using PHP, focusing on the $_GET and $_POST methods for data collection. It outlines the process of connecting to a MySQL database, querying data, and handling errors, as well as the importance of validating form data for security. Additionally, it covers the use of HTTP headers and hidden form elements for data transmission and security measures.

Uploaded by

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

PHP Part 3 - PHP and MySql

This document discusses how to handle HTML forms using PHP, focusing on the $_GET and $_POST methods for data collection. It outlines the process of connecting to a MySQL database, querying data, and handling errors, as well as the importance of validating form data for security. Additionally, it covers the use of HTTP headers and hidden form elements for data transmission and security measures.

Uploaded by

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

Part 3

Dealing with
HTML Forms
Introduction
JavaScript gives us the ability to add dynamic
content to our HTML pages along with the
capability to verify the data that a user input into
a form
MySQL gives us the ability to create tables,
insert, delete, and view (select) data from a
database
PHP gives us the ability to execute code on the
server
Introduction
The link between the user and the PHP scripts is
provided through the arrays $_GET and $_POST
(Note that a "get" can be simulated with a simple URL
since a form with a method equal to "get" simply sends
the data as a URL)
The last link to be addressed is between the PHP script
at the MySQL.
That’s what we’re doing today!
PHP Forms - $_GET
Function
> 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 (it will be displayed in
the browser's address bar) and has limits on the
amount of information to send (max. 100
characters).
PHP Forms - $_GET
Function

Notice how the URL carries the information after the file name.
PHP Forms - $_GET
Function
The "welcome.php" file can now use the $_GET
function to collect form data (the names of the form
fields will automatically be the keys in the $_GET
array)
PHP Forms - $_GET
Function
> When using method="get" in HTML forms, all
variable names and values are displayed in the
URL.
> This method should not be used when sending
passwords or other sensitive information!
> However, because the variables are displayed in
the URL, it is possible to bookmark the page. This
can be useful in some cases.
> The get method is not suitable for large variable
values; the value cannot exceed 100 chars.
PHP Forms - $_POST
Function
> The built-in $_POST function is used to collect
values from a form sent 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.
> Note: However, there is an 8 Mb max size for the
POST method, by default (can be changed by setting
the post_max_size in the php.ini file).
Dealing with HTML
Forms (1)

And here is what the code of action.php might look like:


PHP Forms - $_POST
Function
htmlspecialchars() makes sure any characters that
are special in html are properly encoded so people
can't inject HTML tags or JavaScript into your page.

For the age field, since we know it is a number, we


can just convert it to an integer which will
automatically get rid of any stray characters. The
$_POST['name'] and $_POST['age'] variables are
automatically set for you by PHP.
Dealing with HTML
Forms (2)
HTML Forms (GET and POST)
◦ form is submitted to a PHP script
◦ information from that form is automatically made available to
the script
◦ forms.php

<form action="foo.php" method="POST">


Name: <input type="text" name="username"><br>
Email: <input type="text" name="email"><br>
<input type="submit" name="submit"
value="Submit me!">
</form>
Dealing with HTML
Forms (2 Cont.) Forms –
foo.php
<?php
print $_POST['username'];
print $_REQUEST['username'];
import_request_variables('p', 'p_');
print $p_username;

// Available since PHP 3. As of PHP 5.0.0, these long


// predefined variables can be disabled with the
// register_long_arrays directive.

print $HTTP_POST_VARS['username'];

// Available if the PHP directive register_globals = on.


// As of PHP 4.2.0 the default value of
// register_globals = off.
// Using/relying on this method is not preferred.

print $username; ?>


Dealing with HTML
Forms (3)
info_form.php
<form action=“show_answers.php” method="POST">
Your name: <input type="text" name="name" />
Your age: <input type="text" name="age" />
<input type="submit">
</form>
show_answers.php
Hi
<?php echo $_POST["name"]; ?>.
You are <?php echo $_POST["age"]; ?> years old.
Creating
MySql
Database and
Tables
MySQL Processing
Remember the process for accessing data from a
database using MySQL:
Log onto MySQL:
"mysql -u username -p password"
Select a database to work with:
"use database"
Send a query to one or more tables:
"select ..."
MySQL displays results in text on the display
When your finish, exit MySQL using “exit”
PHP Access to MySQL
The PHP libraries contain functions that allow us to do
each of MySQL operations above:
 Logging onto MySQL:
$connection = mysqli_connect ("host_URL", "username",
"password");
 Selecting a database:
mysqli_select_db("dbname", $connection);
 Querying a table:
$result = mysqli_query("SELECT * FROM tablename",
$connection);
 Receiving results: use $result to access data
 Exiting MySQL:
mysqli_close ($connection);
Logging onto MySQL
Using PHP
Syntax:
$connection = mysqli_connect ("host_URL", "username", "password");
Connecting to the server using the function mysqli_connect()
takes three parameters:
◦ host_URL is the domain name of the MySQL host.
◦ "localhost" can be used if MySQL is installed on the same server as the PHP
engine
◦ "username" represents the username that has privileges to access the
database
◦ "password" is the password for the username

$connection is a variable that is used as a reference to the connection once


it has been made.
Selecting MySQL
Database Using PHP
Syntax:
mysqli_select_db("dbname", $connection);

Selecting a database using the function


mysqli_select_db() takes two parameters:
◦ "dbname" identifies the name of the database
◦ $connection identifies the connection resource you declared
when you established a connection to the MySQL server
Querying a Table
Using PHP
Syntax:
$result = mysqli_query("SELECT * FROM tablename", $connection);

•Unfortunately, the output $result from the previous


function doesn’t provide you with anything beyond a
reference to the resource.

•We need to use the function mysql_fetch_array() to access


the records returned from the query.
Retrieving the Query
Data
The mysqli_fetch_array() function fetches a result row as
an associative array, a numeric array, or both.
Syntax:
$record = mysqli_fetch_array($result [, int result_type]);
$record = mysqli_fetch_array( result,resulttype);

resulttype:

MYSQLI_ASSOC
MYSQLI_NUM
MYSQLI_BOTH
Retrieving the Query Data
(continued)
Pulling a record from the result of a query requires at least
one parameter:
◦ $result is the reference to the query performed by calling the function
mysqli_query()
◦ result_type is an optional field that defines how the array will be
returned.
◦ Using MYSQLi_NUM here will return an array with integer indices/keys.
◦ Using MYSQLi_ASSOC here will return an array using the field names as
indices/keys.
◦ Using MYSQLi_BOTH here will return an array with two elements for every field,
one with integer indices/keys and one using the field names.

◦ Default is MYSQLi_BOTH.
Retrieving the Query Data
(continued)
MYSQLI_NUM is a constant in PHP associated with a mysqli_result.
MYSQLI_NUM specifies that the return array should use numeric keys for the array, instead of
creating an associative array.
Assuming you have two fields in your database table,
"first_field_name" and "second_field_name", with the content "first_field_content" and
"second_field_content"...

$result->fetch_array(MYSQLI_NUM);
fetches each row of the result like this:
array( 0 => "first_field_content", 1 => "second_field_content" );

Alternatively...
$result->fetch_array(MYSQLI_ASSOC);
fetches an array like this:
array( "first_field_name" => "first_field_content", "second_field_name" =>
"second_field_content" );

Using the constant MYSQLI_BOTH will fetch both.


mysqli_fetch_array()
<?php
$con=mysqli_connect("localhost","my_username","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s (%s)\n",$row[0],$row[1]);
// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
Closing the
Connection
use the mysqli_close($connection) function.
Syntax:
boolean = mysqli_close($connection);

$connection is the connection resource assigned with


mysql_connect()
The return value is true on success, false on failure.
MySQL Errors
If you made any syntax errors, MySQL
outputs a cryptic message identifying the
error.
Errors will occur for a number of reasons
both during development and after
deploying the software
mysql_errno()
PHP has a number of functions to assist the
programmer in handling MySQL errors.

int mysqli_errno($connection)
◦ returns the numerical value of the error message from the last MySQL
operation.

A zero returned means there was no error.


A list of the integer error codes can be found at:
http://dev.mysql.com/doc/refman/5.0/en/error-handling.html
mysql_error()
If the error number is too cryptic, the programmer can always use
mysqli_error()

string mysqli_error($connection)
returns the text of the error message from last MySQL operation.

This message is similar to the message you received after a syntax error
at the command line MySQL.
die() or
exit() <?php
$site = "https://www.w3schools.com/";
fopen($site,"r")
or die("Unable to connect to $site");
?>

The functions die() and exit() allow a script to exit gracefully.


The two functions are equivalent, i.e., "die" and "exit" are interchangeable.

Syntax:

void exit ( [string or int status] )


die(message)

If status is a string, exit prints the string before stopping the
script
If status is an integer, it will be returned to calling application.
 Status must be between 0 and 254.
 255 is reserved for PHP.
 0 indicates successful operation.
Other MySQL PHP
Functions
int mysqli_num_fields ($result) retrieves the number of fields from a
query.
int mysqli_num_rows ($result) retrieves the number of rows from a
result set. Only works with a SELECT statement.
int mysqli_affected_rows ($result) retrieves the number of rows
affected by the last INSERT, UPDATE or DELETE query.

Many more functions


Validating Form Data
Although the HTML form might have JavaScript used at
the form to validate data, it is a good idea to validate form
data at the server side too.
Validating HTML form data:
◦ prevents erroneous output
◦ is critical to security
◦ is not to be trusted entirely

To eliminate confusion, all forms should indicate to user


which fields are required and, where applicable, the
format and type of information a field is expecting.
Methods to Validate Form
Data
isset() tests if a variable has a value.
if (isset($var))
{
// $var has a value.
}
else
{
// $var does not have a value.
}

Unfortunately, isset() will return a true if the variable is


set to an empty string.
Methods to Validate Form
Data (continued)
To avoid empty strings, use the string function strlen().

$input = stripslashes($_POST['name']);
if (strlen($input) > 0)
{
// User input a value.
}
else
{
// User did not input a value
}
Did the User Input a
Number?
To test if a submitted value is a number, use
the is_numeric() function.
is_numeric() returns a boolean true if the
value is a number.
How to Validate Form
Data
isset() tests if a variable has a value.

if (isset($var))
{
// $var has a value.
}
else
{
// $var does not have a value.
}
Unfortunately, isset() will return a true if the variable is set to an empty
string.
To avoid empty strings, use the string function strlen().
How to Validate Form Data
(continued)
To avoid empty strings, use the string function strlen().

$input = stripslashes($_POST['name']);
if (strlen($input) > 0)
{
// User input a value.
}
else
{
// User did not input a value
}
Did the User Input a
Number?
To test if a submitted value is a number, use the
is_numeric() function.
is_numeric() returns a boolean true if the value is a
number.
Hidden Form Elements
Hidden form elements can be used to pass data to a PHP script without
allowing the user to see it.
This can be used to identify the form that requested the page or
passing other constants to the server side script.
Never use hidden elements to store secure information as the HTML
can be viewed by the client.
Verifying the Client
$_SERVER['HTTP_REFERER'] returns the address of the page that referred the user
to this script.
$_SERVER['REQUEST_METHOD'] returns the method of the form used to refer the
user to this script.
$_SERVER['REMOTE_ADDR'] returns the IP address of machine originating request.
Can use this to limit which machines have access to your PHP script.
HTTP Headers
HyperText Transfer Protocol (HTTP) is the protocol
that defines how servers and clients communicate.
When a browser requests a Web page, it receives a
series of HTTP headers containing information about
the transaction.
PHP's built-in function header() allows a server-side
script to provide a custom header.
These headers can be used for authentication
HTTP Headers (continued)

Since PHP sends output to the client as it is generated, and


since headers must be sent before the HTML file itself, the
header() function must be executed before the script outputs
anything.
Failure to do this results in an error message to the user.
To avoid this, use the headers_sent() function, which checks
whether or not data has been sent to the Web browser.

if (!headers_sent())
header ("Location: http://www.url.com/a.php");
else
echo "Unable to redirect you.";

You might also like