PHP Part 3 - PHP and MySql
PHP Part 3 - PHP and MySql
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)
print $HTTP_POST_VARS['username'];
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" );
// 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);
int mysqli_errno($connection)
◦ returns the numerical value of the error message from the last MySQL
operation.
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");
?>
Syntax:
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.
$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)
if (!headers_sent())
header ("Location: http://www.url.com/a.php");
else
echo "Unable to redirect you.";