Introducing Database Systems and Web - L32
Introducing Database Systems and Web - L32
Introducing Database Systems and Web - L32
Systems and
Web
(15B11CI312)
Database Systems and Web
PHP
Topics Covered
PHP
PHP Variables & Operators
PHP If / If…else / Switch Statements
Loops in PHP
Arrays & Fnctions in PHP
HTML forms & PHP
What is PHP?
PHP is probably the most popular scripting language on the web.
It is a server-sided language.
PHP doesn't get executed on your computer, but on the computer you requested the page from. The
results are then handed over to you, and displayed in your browser.
PHP stands for is "Hypertext Pre-processor”, but that would make it HPP. An alternative explanation
is that the initials come from the earliest version of the program, which was called Personal Home
Page Tools.
WHAT You Need to get started?
Before you can write and test your PHP scripts, there's one thing you'll need - a server!
Since PHP is a server-sided scripting language, you either have to get some web space with a hosting
company that supports PHP, or make your computer pretend that it has a server installed.
Wampserver allows you to test your PHP scripts on your own computer.
The WAMP of Wampserver stands for Windows, Apache, MySQL, PHP. It installs everything you
need, if you have a Windows PC.
Your first PHP script
<html><head>
</head>
<body>
<?php
?>
</body>
</html>
When you've finished typing it all, save the page as first.php. Then Run the script. Remember: when you're saving your work, save it to the WWW folder
(Wampserver). To run the page, start your browser up and type this in the address bar: http://localhost/first.php
If you've created a folder inside the www folder, then the address to type in your browser would be something like: http://localhost/FolderName/first.php
Echo
The PHP command ‘echo’ is used to output the parameters
passed to it
◦ The typical usage for this is to send data to the client’s web-browser
PHP Variables
A variable is just a storage area.
$mr_coats = 10;
> In PHP, a variable does not need to be declared before adding a value to it.
> In the example above, you see that you do not have to tell PHP which data type the variable is.
> PHP automatically converts the variable to the correct data type, depending on its value.
We've put the PHP in the BODY section of an HTML page. Scripts can also, and often do, go between the
HEAD section of an HTML page. You can also write your script without any HTML. But before a browser can
recognize your script, it needs some help. You have to tell it what kind of script it is. Browsers recognize PHP
by looking for this punctuation (called syntax): <?php ?>
<?php <?php
//--------------TESTING VARIABLES------------ /* --------------TESTING VARIABLES------------
$test_String = "It Worked!"; Use this type of comment if you want to spill over to more
print($test_String); than one line.
?> Notice how the comment begin and end.
*/
$test_String = "It Worked!";
print($test_String);
?>
PHP Concatenation
Use a period to join strings into one.
<?php
$first_number = 10;
$direct_text = 'My variable contains the value of ';
print($direct_text . $first_number);
?>
-----------------------------------------------------------------------------------------------------------------------------------
<?php
$first_number = 10;
> Arithmetic
> Assignment
> Comparison
> Logical
COMPARISON OPERATORS
Logical operators
Operator precedence
Example
<?php
$first_number = 10;
$second_number = 20;
?>
=== and !==
In recent editions of PHP, two new operators have been introduced: the triple equals sign ( = = =) and an exclamation, double equals ( != =). These are
used to test if one value has the same as another AND are of the same type. An example would be:
$number = 3;
$text = ‘3';
print("Same");
else {
So this asks, "Do the variables match exactly?" Since one is text and the other is a number, the answer is "no", or false.
PHP Conditional Statements
> if statement - use this statement to execute some code only if a specified condition is true
> if...else statement - use this statement to execute some code if a condition is true and another code if
the condition is false
> if...elseif....else statement - use this statement to select one of several blocks of code to be executed
> switch statement - use this statement to select one of many blocks of code to be executed
PHP If Statements
<?PHP
$kitten_image = 1;
$church_image = 0;
if ($kitten_image == 1) {
?>
There can be multiple if statements in a PHP script.
if ... else Statements
<?PHP
$kitten_image = 0;
$church_image = 1;
if ($kitten_image == 1) {
else {
?>
SWITCH STATEMENT
<?php
$picture ='church';
switch ($picture) {
case 'kitten':
print('Kitten Picture');
break;
case 'church':
print('Church Picture');
break;
default:
?>
PHP Loops
> while - loops through a block of code while a specified condition is true
> do...while - loops through a block of code once, and then repeats the loop as long as a specified
condition is true
> foreach - loops through a block of code for each element in an array
FOR Loops
for (start value; end value; update expression) {
<?PHP
$counter = 0;
$start = 1;
$counter = $counter + 1;
?>
WHILE & Do… while Loops
Here’s a while loop that prints out the 2 times table.
$start = 1;
$times = 2;
$answer = 0;
print ($start . " times " . $times . " = " . $answer . "<BR>");
$start++;
do
statement
while (condition)
PHP Array
$Order_Number = array( );
This line of code is telling PHP to set up an array, and give it the name $Order_Number.
Arrays work by having a position, and some data for that position. In the above array, "Autumn" is in
position zero, "Winter" is in position 1, "Spring" is in position 2, and "Summer" is in position 3.
The first position is always zero, unless you tell PHP otherwise. Position is known as a Key. The Key
then has a value attached to it. You can specify your own numbers for the Keys.
$seasons = array( 1 => "Autumn", 2 => "Winter", 3 => "Spring", 4 => "Summer" );
You can store text and numbers in the same array:
$Array_Name = array(1 => 10, 2 => "Spring", 3 => 30, 4 => "Summer");
The above array would then look like this:
1=> 10,
2=> "Spring",
3=> 30,
4=> "Summer”
Method two – Assign values to an array
$seasons = array();
$seasons[ ]="Autumn";
$seasons[ ]="Winter";
$seasons[ ]="Spring";
$seasons[ ]="Summer";
Associative Array in PHP
When you use text for the keys, you're using an Associative array; when you use numbers for the keys,
you're using a Scalar array.
$full_name = array( );
$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
Look at the keys and values now:
David => "Gilmour",
Nick => "Mason",
Roger => "Waters",
Richard => "Wright"
Arrays and PHP For Each Loops
$full_name = array( );
$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
}
Sorting PHP Array values
asort() - for sorting associative array
print $random_key;
?>
The PHP count function
$seasons = array("Autumn", "Winter", "Spring", "Summer");
$array_count = count($seasons);
print $seasons[$key_Number];
}
Splitting a line of text in PHP
explode( separator, string_to_split )
$text_line = explode(",",$text_line);
}
Joining text in PHP
If you have a line of text in an array, you can join it all together to form a single line of text. This is
just the opposite of explode.
print($new_textline);
PHP and Escaping Characters
<?PHP
$string = 'John's Car'; //Observe the single quotes
print $string;
?>
To solve the problem, you could use double quotes on the outside:
$string = "John's Car";
Or you could escape the apostrophe. You escape a character by typing a "slash" before it:
$string = 'John\'s Car';
PHP String functions
chr( ) Convert an ASCII value to a its equivalent character
ord( ) Find out what the ASCII value of a character is
echo( ) An alternative to the print statement
similar_text( ) Tells you how similar two strings of text are
str_repeat( ) Repeat a character a specified number of times
str_replace( ) Replace one string with another
str_word_count( ) Tells you how many words a string has
strlen( ) Gets the length of a string
substr( ) Grab a number of character from a string
PHP Functions
function function_name() {
-------------------------------------------------------------------------------------------------------------------------------------------------------------
<?PHP
display_error_message($error_text);
function display_error_message($error_text) {
print $error_text;
?>
Getting values out of PHP functions
<?PHP
$total_spent = 120;
$order_total = calculate_total($total_spent);
print $order_total;
function calculate_total($total_spent) {
$discount = 0.1;
$total_charged = $discount_total;
else {
$total_charged = $total_spent;
return $total_charged;
?>
By Ref, By Val
<?PHP
$Variable_Value = 10;
example($Variable_Value);
function example($Variable_Value) {
?>
When you run the code, it will print out this:
Before the function call = 10
Inside of the function = 20
After the function call = 10
Make one small change to your script: function example(&$Variable_Value) {…… }
When you run the script, it now print out the following:
Before the function call = 10
Inside of the function = 20
After the function call = 20
Html forms and php
<html>
<head>
</head>
<body>
</FORM>
</body>
</html>
PHP and the Method Attribute
of HTML Forms
<FORM NAME ="form1" METHOD =" " ACTION = "">
The Method attribute is used to tell the browser how the form information should be sent. The two most popular methods you can use are GET and POST. But our
METHOD is blank. So change it to this:
To see what effect using GET has, save your work again and then click the Submit button on your form. You should see this:
The thing to notice here is the address bar. After basicForm.php, we have the following: ?Submit1=Login
This is a consequence of using the GET method. The data from the form ends up in the address bar. You'll see a question mark, followed by form data. In the image above,
Submit1 was the NAME of the button, and Login was the VALUE of the button (the text on the button). This is what is being returned by the GET method. You use the
GET method when the data you want returned is not crucial information that needs protecting.
PHP and the Post Attribute of
HTML Forms
<FORM NAME ="form1" METHOD ="POST" ACTION = "">
Using POST means that the form data won't get appended to the address in the address bar for all to
see.
if the data is not sensitive then use GET, otherwise use POST.
PHP and the Action Attribute
of HTML Forms
The Action attribute is crucial. It means, "Where do you want the form sent?". If you miss it out, your
form won't get sent anywhere. You can send the form data to another PHP script, the same PHP script,
an email address, a CGI script, or any other form of script.
In PHP, a popular technique is to send the script to the same page that the form is on – send it to itself.
So we're going to be sending the form data to exactly the same page as the one we have loaded – to
itself. We'll put some PHP on the page to handle the form data.
Returning value from a Form
element
To return data from a HTML form element, you use the following syntax: $_POST['formElement_name'];
$Your_Variable = $_GET['formElement_name'];
If the user just refreshed the page, then no value will be set for the Submit button. If the user did click
the Submit button, then PHP will automatically return a value.
The HTML ACTION attribute and PHP
Create the following page, and call it basicForm2.php. This is your HTML. Notice the ACTION attribute.
<html>
<head>
</head>
<body>
</FORM>
</body>
</html>
Now create the following page, and call it submitForm.php:
<?PHP
$username = $_POST['username'];
if ($username == "letmein") {
else {
?>
Posting form data to a different PHP script is a way to keep the HTML and PHP separate. But there is a problem with it, which you will have
noticed: the script gets executed on a new page. That means your form will disappear! We'll keep the PHP and HTML together. But there will be
times when you do want to send form data to a different PHP page.
Data retention
If you look at the VALUE attribute of the text box in the HTML form, you'll see that it's set to "username". Because
the form gets posted back to itself, this value will keep re-appearing in the textbox when the page is submitted.
Worse, if you've left the Value attributes empty then everything the user entered will disappear. This can be very
annoying, if you're asking the user to try again. Better is to POST back the values that the user entered.
To post the details back to the form, and thus keep the data the user has already typed out, you can use this:
Our new line of HTML for our textbox reads like this:
In other words, we're now printing out the VALUE attribute with PHP code.
radiobutton
<html>
<head>
<title>Radio Buttons</title>
</head>
<body>
<P>
</FORM>
</body>
</html>
To get the value of a radio button with PHP code, again you access the NAME attribute of the HTML
form elements. In the HTML above, the NAME of the Radio buttons is the same – "gender".
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['gender'];
print $selected_radio;
}
You can get which browser the user has with this:
$agent = $_SERVER["HTTP_USER_AGENT"];
Here's a script that checks which of two browsers a user has:
$agent = $_SERVER['HTTP_USER_AGENT'];
if ( strpos( strtoupper($agent), 'MSIE') ) {
print "Internet Explorer";
}
else if (strpos(strtoupper($agent), 'FIREFOX')) {
print "Firefox";
}
else {
print $agent;
}
A script to check for blank text boxes
<html>
<head>
</head>
<body>
<?php
$first ="";
$second = "";
function display_error_message($user_text) {
if ($user_text = = "") {
else {
}
if ($_SERVER['REQUEST_METHOD'] = = 'POST'){
$first = trim($_POST['first']);
$second = trim($_POST['second']);
display_error_message($first);
display_error_message($second);
}
?>
</body>
<FORM Method = "POST" action ="formFunction.php">
First Name: <INPUT TYPE = "text" name = "first" value ="<?=$first?>">
Surnmae: <INPUT TYPE = "text" name = "second" value ="<?=$second?>">
<input type="submit" name="Submit" value="Submit">
</FORM>
</html>
PHP Server Variables
PHP stores a list of information about the server. This will include things like, the browser the
visitor is using, the IP address, and which web page the visitor came from. Here's a script to try
with those three Server Variables:
$referrer = $_SERVER['HTTP_REFERER'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
$_SERVER['Server_Variable']
The server variables are held in an array (associative), so you can use a foreach loop to get a list of all
available ones. Try this script:
<?PHP
foreach($_SERVER as $key_name => $key_value) {
print $key_name . " = " . $key_value . "<br>";
}
?>
What the script does is to loop round all the server variables and print out the keys and values in the
SERVER array.
Run a PHP program in XAMPP Server
Step1
Install XAMPP
Step2
Now create your first php program in xampp and name it with .php extension such as “add.php”:
Step4
Now double click on “XAAMP CONTROL PANEL” on desktop and START “Apache” (icon
also appears on the bottom)
Step5
Type localhost on your browser and press enter: It will show the following:
Step6
❖Lynn Beighley & Michael Morrison, “Head First PHP and MySQL”, First Edition, O’Reilly.
❖https://www.w3schools.com/php/DEFAULT.asp
❖https://www.tutorialspoint.com/php/index.htm
❖https://www.phpmyadmin.net