0% found this document useful (0 votes)
43 views

Displaying Script Results

The document discusses displaying the results of PHP scripts through echo and print statements. It explains: - echo and print statements output text to the web page returned to the client. They are built-in PHP language constructs. - The statements are identical except print returns a value while echo does not. They can output multiple values separated by commas. - To output results from multiple PHP sections on a page, the code should be wrapped in separate opening and closing tags with the <?php ?> syntax.

Uploaded by

Anthony Bards
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)
43 views

Displaying Script Results

The document discusses displaying the results of PHP scripts through echo and print statements. It explains: - echo and print statements output text to the web page returned to the client. They are built-in PHP language constructs. - The statements are identical except print returns a value while echo does not. They can output multiple values separated by commas. - To output results from multiple PHP sections on a page, the code should be wrapped in separate opening and closing tags with the <?php ?> syntax.

Uploaded by

Anthony Bards
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/ 78

Displaying Script Results

To return to the client the results of any


processing that occurs within a PHP code block,
you must use an echo() statement or the
print() statement
The echo() and print() statements create
new text on a Web page that is returned as a
response to a client

Displaying Script Results


(continued)

PHP Diagnostic Information Web page


2

Displaying Script Results


(continued)
The echo() and print() statements are
language constructs of the PHP programming
language
A programming language construct refers to a
built-in feature of a programming language
The echo() and print() statements are
virtually identical except:
The print() statement returns a value of 1 if
it is successful
It returns a value of 0 if it is not successful
3

Displaying Script Results


(continued)
Use the echo() and print() statements to
return the results of a PHP script within a Web
page that is returned to a client
A text string, or literal string, is text that is
contained within double or single quotation
marks
To pass multiple arguments to the echo() and
print() statements, separate them with
commas like arguments passed to a function
4

Creating Multiple Code Declaration


Blocks
For multiple script sections in a document,
include a separate code declaration block for
each section
...
</head>
<body>
<h1>Multiple Script Sections</h1>
<h2>First Script Section</h2>
<?php echo <p>Output from the first script section.</p>;
?>
<h2>Second Script Section</h2>
<?php echo <p>Output from the second script section.</p>
;?>
</body>
</html>

Creating Multiple Code Declaration


Blocks (continued)
PHP code declaration blocks execute on a Web
server before a Web page is sent to a client
...
</head>
<body>
<h1>Multiple Script Sections</h1>
<h2>First Script Section</h2>
<p>Output from the first script section.</p>
<h2>Second Script Section</h2>
<p>Output from the second script section.</p>
</body>
</html>
6

Creating Multiple Code Declaration


Blocks (continued)

Figure 1-9 Output of a document with two PHP script sections


7

Case Sensitivity in PHP


Programming language constructs in PHP are
mostly case insensitive
<?php
echo <p>Explore <strong>Africa</strong>, <br />;
Echo <strong>South America</strong>, <br />;
ECHO and <strong>Australia</strong>!</p>;
?>

Adding Comments to a PHP Script


Comments are nonprinting lines placed in code
such as:

The name of the script


Your name and the date you created the program
Notes to yourself
Instructions to future programmers who might
need to modify your work

Adding Comments to a PHP Script


(continued)
Line comments hide a single line of code
Add // or # before the text

Block comments hide multiple lines of code


Add /* to the first line of code
And */ after the last character in the code

10

Adding Comments to a PHP Script


(continued)
<?php
/*
This line is part of the block comment.
This line is also part of the block comment.
*/
echo <h1>Comments Example</h1>; // Line comments can
follow
code statements
// This line comment takes up an entire line.
# This is another way of creating a line comment.
/* This is another way of creating
a block comment. */
?>

11

Using Variables and Constants


The values stored in computer memory are
called variables
The name you assign to a variable is called an
identifier and it:

Must begin with a dollar sign ($)


Cannot begin with an underscore (_) or a number
Cannot include spaces
Is case sensitive

12

Declaring and Initializing Variables


Specifying and creating a variable name is
called declaring the variable
Assigning a first value to a variable is called
initializing the variable
In PHP, you must declare and initialize a variable
in the same statement:
$variable_name = value;

13

Displaying Variables
To print a variable with the echo() statement,
pass the variable name to the echo()
statement without enclosing it in quotation marks:
$VotingAge = 18;
Echo $VotingAge;

To print both text strings and variables, send


them to the echo() statement as individual
arguments, separated by commas:
echo "<p>The legal voting age is ", $VotingAge, ".</p>";

14

Displaying Variables
To print text strings and variables, you can send
them to the echo() statement as one argument
enclosed in double quotes:
echo "<p>The legal voting age is $VotingAge.</p>";
The legal voting age is 18.

To print text strings and the variable name, you


can send them to the echo() statement as one
argument enclosed in single quotes:
echo <p>The legal voting age is $VotingAge.</p>;
The legal voting age is $VotingAge
15

Modifying Variables
You can modify a variables value at any point in a
script
$SalesTotal = 40;
echo "<p>Your sales total is
$$SalesTotal</p>";
$SalesTotal = 50;
echo "<p>Your new sales total is
$SalesTotal</p>";

16

Defining Constants
A constant contains information that does not
change during the course of program execution
Constant names do not begin with a dollar sign
Constant names use all uppercase letters
Use the define() function to create a constant
define("CONSTANT_NAME", value);
define("VOTING_AGE",18);
define("VOTING_AGE",18,TRUE);

The value you pass to the define() function


can be a text string, number, or Boolean value
17

Working with Data Types


A data type is the specific category of
information that a variable contains
Data types that can be assigned only a single
value are called primitive types

18

Working with Data Types


(continued)
The PHP language supports:
A resource data type a special variable that
holds a reference to an external resource such
as a database or XML file
Reference or composite data types, which
contain multiple values or complex types of
information
Two reference data types: arrays and objects

19

Working with Data Types


(continued)
Strongly typed programming languages
require you to declare the data types of variables
Static or strong typing refers to data types that
do not change after they have been declared
Loosely typed programming languages do
not require you to declare the data types of
variables
Dynamic or loose typing refers to data types
that can change after they have been declared
20

Numeric Data Types


PHP supports two numeric data types:
An integer is a positive or negative number with
no decimal places (-250, 2, 100, 10,000)
A floating-point number is a number that
contains decimal places or that is written in
exponential notation (-6.16, 3.17, 2.7541)
Exponential notation, or scientific notation, is
short for writing very large numbers or numbers
with many decimal places (2.0e11)
21

Boolean Values
A Boolean value is a value of true or false
It decides which part of a program should
execute and which part should compare data
In PHP programming, you can only use true or
false
In other programming languages, you can use
integers such as 1 = true, 0 = false

22

Dynamic Typing
$Variable
$Variable
$Variable
$Variable
$Variable

=
=
=
=
=

"Hello World";
8;
5.367;
TRUE;
NULL;

23

Using Autoglobals
PHP includes various predefined global arrays,
called autoglobals or superglobals
Autoglobals contain client, server, and
environment information that you can use in
your scripts
Autoglobals are associative arrays arrays
whose elements are referred to with an
alphanumeric key instead of an index number

24

Using Autoglobals (continued)


PHP autoglobals

25

Using Autoglobals (continued)


$_GET is the default method for submitting a
form. $_GET appends form data as one long
string to the URL specified by the action attribute
google.com/search?hl=en&source=hp&q=php
$_GET and $_POST allow you to access the
values of forms that are submitted to a PHP script

26

Using Autoglobals (continued)


$_POST sends form data as a transmission
separate from the URL specified by the form action
attribute
<formaction=submitpage.php"
method=post">
<inputtype="text"name=variable1">
<inputtype="text"name=variable2">
<inputtype="text"name=name">
<inputtype="submit">
</form>
27

Autoglobals
$_SERVER[PHP_SELF];
$_SERVER[SERVER_SOFTWARE];
$_SERVER[SERVER_PROTOCOL];
$_GET[name];
$_GET[address];

28

Making Decisions
Decision making or flow control is the process
of determining the order in which statements
execute in a program
The special types of PHP statements used for
making decisions are called decision-making
statements or decision-making structures

if Statements
Used to execute specific programming code if
the evaluation of a conditional expression
returns a value of TRUE
The syntax for a simple if statement is:
if (conditional expression)
statement;

if Statements (continued)
Contains three parts:
the keyword if
a conditional expression enclosed within
parentheses
the executable statements

A command block is a group of statements


contained within a set of braces
Each command block must have an opening
brace ( { ) and a closing brace ( } )

if Statements (continued)
$ExampleVar = 5;
if ($ExampleVar == 5) {
// condition evaluates to 'TRUE'
echo " <p>The condition evaluates to true.</p> ";
echo '<p>$ExampleVar is equal to ',
" $ExampleVar.</p> ";
echo " <p>Each of these lines will be printed.</p> ";
}
echo " <p>This statement always executes after the if
statement.</p> ";

if...else Statements
An if statement that includes an else clause is
called an if...else statement
An else clause executes when the condition in
an if...else statement evaluates to FALSE
The syntax for an if...else statement is:
if (conditional expression)
statement;
else
statement;

if...else Statements
(continued)
An if statement can be constructed without the
else clause
The else clause can only be used with an if
statement
$Today = " Tuesday ";
if ($Today == " Monday ")
echo " <p>Today is Monday</p> ";
else
echo " <p>Today is not Monday</p> ";

Nested if and if...else


Statements
When one decision-making statement is
contained within another decision-making
statement, they are referred to as nested
decision-making structures
if ($SalesTotal >= 50)
if ($SalesTotal <= 100)
echo " <p>The sales total is between
50 and 100, inclusive.</p> ";

switch Statements
Control program flow by executing a specific set
of statements depending on the value of an
expression
Compare the value of an expression to a value
contained within a special statement called a
case label
A case label is a specific value that contains
one or more statements that execute if the value
of the case label matches the value of the switch
statements expression

switch Statements (continued)


Consist of the following components:

The switch keyword


An expression
An opening brace
One or more case labels
The executable statements
The break keyword
A default label
A closing brace

switch Statements (continued)


The syntax for the switch statement is:
switch (expression) {
case label:
statement(s);
break;
case label:
statement(s);
break;
...
default:
statement(s);
break;
}

switch Statements (continued)


A case label consists of:
The keyword case
A literal value or variable name
A colon (:)

A case label can be followed by a single


statement or multiple statements
Multiple statements for a case label do not need
to be enclosed within a command block

switch Statements (continued)


The default label contains statements that
execute when the value returned by the switch
statement expression does not match a case
label
A default label consists of the keyword
default followed by a colon (:)

switch Statements (continued)


$product_name = "Processors";
switch ($product_name)
{
case "Video Cards":
echo "Video cards range from $50 to $500";
break;
case "Processors":
echo Processors range from $100 to $1000";
break;
default:
echo "Sorry, we don't carry $product_name in our
catalog";
break;
}
41

PHP Form Handling


The PHP superglobals $_GET and $_POST are used to
collect form-data.
EX:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

welcome.php

<html>
<body>
<?php
$name=$_POST["name"];
$email=$_POST["email"];
echo "Your name is ".$name."<br/>";
echo "Your email is ".$email."<br/>";
?>

</body>
</html>

welcome.php
isset Determine if a variable is set and is not NULL
<html>
<body>
<?php

if(isset($_POST["name"]) && isset($_POST["email"])


{
$name=$_POST["name"];
$email=$_POST["email"];
echo "Your name is ".$name."<br/>";
echo "Your email is ".$email."<br/>";
}
?>
</body>
</html>

<html>
<body>
<form action="welcome.php" method= "get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

<html>
<body>
<?php
$name=$_GET["name"];
$email=$_GET["email"];
echo "Your name is ".$name."<br/>";
echo "Your email is ".$email."<br/>";
?>

</body>
</html>

GET vs. POST


Both GET and POST are treated as $_GET and
$_POST. These are superglobals, which means that
they are always accessible, regardless of scope and you can access them from any function, class or
file without having to do anything special.
$_GET is an array of variables passed to the current
script via the URL parameters.
$_POST is an array of variables passed to the
current script via the HTTP POST method.

When to use GET?


Information sent from a form with the GET method is
visible to everyone (all variable names and values are
displayed in the URL). GET also has limits on the
amount of information to send. The limitation is about
2000 characters. However, because the variables are
displayed in the URL, it is possible to bookmark the
page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending
passwords or other sensitive information!

When to use POST?


Information sent from a form with the POST method is
invisible to others (all names/values are embedded
within the body of the HTTP request) and has no limits
on the amount of information to send.
Moreover POST supports advanced functionality such
as support for multi-part binary input while uploading
files to server.
However, because the variables are not displayed in the
URL, it is not possible to bookmark the page.
Note Developers prefer POST for sending form data.

What is the $_SERVER["PHP_SELF"] variable?


The $_SERVER["PHP_SELF"] is a super global
variable that returns the filename of the currently
executing script.
So, the $_SERVER["PHP_SELF"] sends the
submitted form data to the page itself, instead of
jumping to a different page. This way, the user will
get error messages on the same page as the form.

What is the htmlspecialchars() function?


The htmlspecialchars() function converts special
characters to HTML entities. This means that it will
replace HTML characters like < and > with &lt; and
&gt;. This prevents attackers from exploiting the code
by injecting HTML or Javascript code (Cross-site
Scripting attacks) in forms.
for an example

<html>
<body>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>First name: <input type="text" name="firstname" /></p>
<p>Last name: <input type="text" name="lastname" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
</html>
<?php
if(isset($_POST['firstname']) && isset($_POST['lastname']))
{
echo("First name: " . $_POST['firstname'] . "<br />\n");
echo("Last name: " . $_POST['lastname'] . "<br />\n");
}

?>

CENG 449 Lecture 11

<?php
if(isset($_POST['firstname']) && isset($_POST['lastname']))
{
echo("First name: " . $_POST['firstname'] . "<br />\n");
echo("Last name: " . $_POST['lastname'] . "<br />\n");
}
?>
<html>
<body>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>First name: <input type="text" name="firstname" /></p>
<p>Last name: <input type="text" name="lastname" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
</html>

Secure input data


To prevent hackers entering your system, use the following approach while inputting the
data from user
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data); // avoids the blank spaces at the beginning and at the end
$data = stripslashes($data); // stripes slashes
$data = htmlspecialchars($data); // convers special characters such as &lt
return $data;
}
?>

Select Forms:
<html>
<body>
<h4>Art Supply Order Form</h4>
<form action="process.php" method="post">
<select name="item">
<option>Paint</option>
<option>Brushes</option>
<option>Erasers</option>
</select>
Quantity: <input name="quantity" type="text" />
<input type="submit" />
</form>
</body>
</html>

process.php
<html>
<body>
<?php
$quantity = $_POST['quantity'];
$item = $_POST['item'];
echo "You ordered ". $quantity . " " . $item . ".<br />";
echo "Thank you for ordering!";
?>
</body>
</html>

<html>
<body>
<h3>PHP HTML Form radio button Example</h3>
<form name="infoForm" method="POST" action=example.php">
Enter Your Full Name :
<input name="FullName" type="text" placeholder="Fullname"><br/><br/>
You are :
<input name="YourGender" type="radio" value="male" > Male
<input name="YourGender" type="radio" value="female" > Female
<br/>
<br/>
<input name="BtnSubmit" type="submit" value="Submit">
</form>
</body>
</html>

example.php
<html>
<body>
<?php
if(isset($_POST['BtnSubmit']))
{
echo "<h3>Your form data as bellow</h3>";
echo "</br>Your Name: {$_POST['FullName']}";
echo "</br>Your are: {$_POST['YourGender']}";
echo "<hr>";
}
?>
</body>
</html>

CENG 449 Lecture 11

Checkbox example:
<html>
<body>
<h3>PHP HTML Form checkbox Example</h3>
<form action="process.php" method="post">
<input type="checkbox" name="gender" value="Male">Male</input>
<input type="checkbox" name="gender"
value="Female">Female</input>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>

process.php
<html>
<body>
<?php
if (isset($_POST['gender']))
{
echo "Your gender is ";
echo $_POST['gender']; // Displays value of checked checkbox.
}
?>
</body>
</html>

<html>
<body>
<h3>PHP HTML Form button Example</h3>
<form name="infoForm" method="POST" action="process.php">
Enter Your Name :
<input name="FullName" type="text" placeholder="Name"><br/><br/>
Enter Your SurName :
<input name="SurName" type="text" placeholder="Surname"><br/><br/>
<input type="submit" name="save" value="Save">
<input type="submit" name="clear" value="Clear">
<input type="submit" name="update" value="Update">
</form>
</body>
</html>

process.php
<html>
<body>
<?php
if (isset($_POST['save']))
{
echo "Save button is pressed! <br /> ";
}
if (isset($_POST['clear']))
{
echo "Clear button is pressed! <br /> ";
}
if (isset($_POST['update']))
{
echo "Update button is pressed! <br /> ";
}
?>
</body>
</html>

CENG 449 Lecture 11

Mulltiple Selection CheckBox:


<!DOCTYPE html>
<html>
<body>
<p> Please select your book types: </p>
<form name="form1" action="process.php" method="POST">
<input type="checkbox" name="book[]" value="Drama"> Drama <br/>
<input type="checkbox" name="book[]" value="Action and Adventure"> Action and Adventure <br/>
<input type="checkbox" name="book[]" value="Romance"> Romance <br/>
<input type="checkbox" name="book[]" value="Mystery"> Mystery <br/>
<input type="checkbox" name="book[]" value="Horror"> Horror <br/>
<input type="checkbox" name="book[]" value="Guide"> Guide <br/>
<input type="checkbox" name="book[]" value="Science"> Science <br/>
<input type="checkbox" name="book[]" value="History"> History <br/>
<input type="submit" value="SUBMIT">
</form>

</body>
</html>

<?php
$bookArray=$_POST['book'];
echo "Your selected books are <br/>";
foreach ($bookArray as $aBook)
{
echo "$aBook <br>";
}
?>

CENG 449 Lecture 11

PHP and MySQL


MySQL works very well in combination of various
programming languages like PERL, C, C++, JAVA and PHP.
Out of these languages, PHP is the most popular one
because of its web application development capabilities.
PHP provides various functions to access MySQL database
and to manipulate data records inside MySQL database. You
would require to call PHP functions in the same way you call
any other PHP function.
The PHP functions for use with MySQL have the following
general format:
mysql_function(value,value,...);

Following example shows a generic syntax of PHP to call any


MySQL function.
<html>
<head>
<title>PHP with MySQL</title>
</head>
<body>
<?php
$retval = mysql_function(value, [value,...]);
if( !$retval )
{
die ( "Error: a related error message" );
}
// Otherwise MySQL or PHP Statements
?>
</body>
</html>

MySQL Connection using PHP


Script:
connection mysql_connect(server,user,passwd,new_link,client_flag);
<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
</body>
</html>

<html>
<body>
<h3>User Data Form</h3>
<form name="infoForm" method="POST" action= " process.php">
Enter Your Name :
<input name="Name" type="text" placeholder="Name"><br/>
Enter Your SurName :
<input name="Surname" type="text" placeholder="Surname"><br/>
Enter Your Student Number :
<input name="stNumber" type="text" placeholder="Student Number"><br/>
You are :
<input name="YourGender" type="radio" value="male" > Male
<input name="YourGender" type="radio" value="female" > Female
<br/>
<input name="BtnSubmit" type="submit" value="Submit"> <br/><br/>
</form>
</body>
</html>

<?php
$stName=$_POST['Name']; $stSurname=$_POST['Surname']; $stFullName=$Name." ".$Surname;
$stNumber=$_POST['stNumber']; $stGender=$_POST['YourGender'];
$dbhost = "localhost"; $dbuser = "root"; $dbpass = "";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db('studentInfo');
$sql = "INSERT INTO studentInfoTable (stName, stSurname,stFullName,stNumber, stGender)
VALUES ('$stName','$stSurname','$stFullName','$stNumber','$stGender')";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>

Search data in database


<html>
<body>
<h3>User Data Form</h3>
<form name="infoForm" method="POST" action= " process.php">
Enter Name to be Searhed :
<input name=Name" type="text" placeholder="Name"><br/>
<input name="BtnSubmit" type="submit" value="Submit"> <br/>
</form>
</body>
</html>

<?php
$stName=$_POST['Name'];
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db('studentInfo');
$sql = "SELECT * FROM studentInfoTable WHERE stName='$stName'";

$retval = mysql_query( $sql, $conn );


if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval)
{
echo "$row['stName'] $row['stSurname'] <br> ";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>

You might also like