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

DBMS Lab 05

The document outlines a lab focused on programming in PHP, covering key concepts such as PHP basics, data types, expressions, operators, conditionals, and loops. It includes examples and explanations of syntax, variable types, and control structures, along with tasks for practical application. The lab aims to provide a foundational understanding of PHP programming for students.

Uploaded by

mranees5323
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)
7 views

DBMS Lab 05

The document outlines a lab focused on programming in PHP, covering key concepts such as PHP basics, data types, expressions, operators, conditionals, and loops. It includes examples and explanations of syntax, variable types, and control structures, along with tasks for practical application. The lab aims to provide a foundational understanding of PHP programming for students.

Uploaded by

mranees5323
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/ 22

Lab # 05: Programming in PHP

OBJECTIVES OF THE LAB


------------------------------------------------------------------------------------------------------------
This lab aims at the understanding of:

 PHP Basics
 PHP Data Types
 PHP Expressions
 PHP Operators
 PHP Conditionals
 PHP Loops
----------------------------------------------------------------------------------------------------

PHP BASICS

This section of the lab covers PHP syntax, comments, and variables.

Basic Syntax

Semicolons
PHP commands end with a semicolon, like this:

 $x += 10;

One of the most common causes of errors in PHP is forgetting this semicolon. This makes PHP to treat
multiple statements like one statement, which it is unable to understand, prompting it to produce a
Parse error message.

The $ symbol
In PHP, $ must be placed in front of all variables. This is required to make the PHP parser faster, as it
instantly knows whenever it comes across a variable. Whether variables are numbers, strings, or arrays,
they should all look something like those in Example 1.

Example 1: Three Different Types of Variable Assignment

1. <?php
2. $username = "Ali Ahmad";
3. echo $username;
4. $mycount = 1;
5. echo "<br />".$mycount;
6. $team = array('Maqsood', 'Maryam', 'Adam', 'Naila');
7. echo "<br />".$team[0]." ".$team[1]." ".$team[2]." ".$team[3];
8. ?>

Comments

There are two ways to comment PHP code. The first turns a single line into a comment by preceding it
with a pair of forward slashes, like this:

 // This is a comment

This version of the comment feature is a great way to temporarily remove a line of code from a program
that is giving you errors. For example, you could use such a comment to hide a debugging line of code
until you need it, like this:

 // echo "X equals $x";

You can also use this type of comment directly after a line of code to describe its action, like this:

 $x += 10; // Increment $x by 10

When you need multiple-line comments, there’s a second type of comment, which looks like Example 2.

Example 2: A Multiline Comment

1. <?php
2. /* This is a section
3. of multiline comments
4. which will not be
5. interpreted */
6. ?>

The /* and */ pairs of characters can be used to open and close comments almost anywhere inside the
code. Most, if not all, programmers use this construct to temporarily comment out entire sections of
code that do not work or that, for one reason or another, they do not wish to be interpreted.
Variables

Variables are used for storing values, like text strings, numbers or arrays. When a variable is declared, it
can be used over and over again in your script. All variables in PHP start with a $ sign symbol.
In PHP, a variable does not need to be declared before adding a value to it. In Example 1, 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.

String Variables
String value can be assigned to a variable like this:

 $username = "Ali Ahmad";

The quotation marks indicate that “Ali Ahmad” is a string of characters. You must enclose each string in
either quotation marks or apostrophes (single quotes), although there is a subtle difference between
the two types of quote, which is explained later. To see the contents, echo command can be used:

 echo $username;

Or you can assign it to another variable, like this:

 $current_user = $username;

Numeric Variables
Numeric variables contain numbers. For instance:

 $mycount = 17;

Similarly, a floating-point number (containing a decimal point) can be used; the syntax is the same:

 $mycount = 17.5;

The value of $mycount can be assigned to another variable or can be echoed to the web browser.

Arrays
Arrays can be created using array() construct. For instance:

 $team = array('Maqsood', 'Maryam', 'Adam', 'Naila');

$team array contains five strings inside. Each string is enclosed in apostrophes. To know who player 4 is,
following command is used:

 echo $team[3]; // Displays the name Naila


The reason the previous statement has the number 3, not 4, is because the first element of a PHP array
is actually the zero element, so the player numbers will therefore be 0 through 3.

Variable Naming Conventions

Following rules must be practiced when naming variables:

1) A variable name must start with a letter or an underscore "_" -- not a number
2) A variable name can only contain alpha-numeric characters, underscores (a-z, A-Z, 0-9, and _ )
3) A variable name should not contain spaces. If a variable name is more than one word, it should
be separated with an underscore ($my_string) or with capitalization ($myString)

PHP DATA TYPES

All data stored in PHP variables fall into one of eight basic categories, known as data types. A variable’s
data type determines what operations can be carried out on the variable’s data, as well as the amount
of memory needed to hold the data.

PHP supports four scalar data types. Scalar data means data that contains only a single value. Here’s a
list of them, including examples:

Scalar Data Type Description Example


Integer A whole number 15
Float A floating-point number 8.23
String A series of characters “Hello World!”
Boolean Represents either true or false true

PHP supports two compound types. Compound data is data that can contain more than one value. The
following table describes PHP’s compound types:

Compound Data Type Description


Array An ordered map (contains names or numbers mapped to values)
Object A type that may contain properties and methods

Finally, PHP supports two special data types, so called because they don’t contain scalar or compound
data as such, but have a specific meaning:

Special Data Type Description


Resource Contains a reference to an external resource, such as a file or
database
Null May only contain null as a values, meaning the variable explicitly
does not contain any value

Testing Variable Type


You can determine the type of a variable at any time by using PHP’s gettype() function. To use gettype(),
pass in the variable whose type you want to test. The function then returns the variable’s type as a
string. Example 3 shows gettype() in action. A variable is declared, and its type is tested with gettype().
Then, four different types of data are assigned to the variable, and the variable’s type is retested with
gettype() each time:

Example 3: Testing Variable Type Using gettype()

1. $test_var;
2. echo gettype( $test_var ) . “ < br / > ”; // Displays “NULL”
3. $test_var = 15;p
4. echo gettype( $test_var ) . “ < br / > ”; // Displays “integer”
5. $test_var = 8.23;
6. echo gettype( $test_var ) . “ < br / > ”; // Displays “double”
7. $test_var = “Hello, world!”;
8. echo gettype( $test_var ) . “ < br / > ”; // Displays “string”

You can also test a variable for a specific data type using PHP’s type testing functions:

Function Description
is_int( value ) Returns true if value is an integer
is_float( value ) Returns true if value is a float
is_string( value ) Returns true if value is a string
is_bool( value ) Returns true if value is a Boolean
is_array( value ) Returns true if value is an array
is_object( value ) Returns true if value is an object
is_resource( value ) Returns true if value is a resource
is_null( value ) Returns true if value is null

Setting Variable Type


PHP’s settype() function is used to change the type of a variable while preserving the variable’s value as
much as possible. To use settype() , pass in the name of the variable you want to alter, followed by the
type to change the variable to (in quotation marks).
Example 4 shows settype() in action. A variable is declared, and its value is shown. Then, it is converted
into four different types of data including string, integer, float, and Boolean using settype(). Output of
each conversion is also shown.

Example 4: Setting Variable to Different Types

1. $test_var = 8.23;
2. echo $test_var . “ < br / > ”; // Displays “8.23”
3. settype( $test_var, “string” );
4. echo $test_var . “ < br / > ”; // Displays “8.23”
5. settype( $test_var, “integer” );
6. echo $test_var . “ < br / > ”; // Displays “8”
7. settype( $test_var, “float” );
8. echo $test_var . “ < br / > ”; // Displays “8”
9. settype( $test_var, “boolean” );
10. echo $test_var . “ < br / > ”; // Displays “1”

---------------------------Task 5.1---------------------------
In contrast to settype(), there is another method that causes a variable’s value to be treated as
a specific type. It is known as type casting. Note that the variable itself remains unaffected
during type casting. Consider the following variable:

 $test_var = 8.23;

Type cast this variable’s value to integer, string, and Boolean and show result using echo.

---------------------------Task 5.2---------------------------
Use and Specify the purpose of following functions:
1) intval( value )
2) floatval( value )
3) strval( value )

PHP EXPRESSIONS

An expression in PHP is anything that evaluates to a value; this can be any combination of values,
variables, operators, and functions. Here are some examples of expressions:

 $x + $y + $z
 $x
 5
 gettype( $test_var )

Literals
The simplest form of an expression is a literal, which simply means something that evaluates to itself,
such as the number 73 or the string "Hello". The number 5 above is an example of literal.

PHP OPERATORS

Operators in PHP can be grouped into ten types, as show in Table 5.1.

TABLE 5.1 PHP OPERATORS


Type Description
Arithmetic Perform common arithmetic operations, such as addition and subtraction
Assignment Assign values to variables
Bitwise Perform operations on individual bits in an integer
Comparison Compare values in a Boolean fashion
Error Control Affect error handling
Execution Cause execution of commands as though they are shell commands
Incrementing/Decrementing Increment or decrement a variable’s value
Logical Boolean operators such as and, or, and not
String Concatenates strings
Array Perform operations on arrays

Arithmetic and Increment/Decrement Operators


Figure 5.1 and Figure 5.2 shows the arithmetic and increment/decrement operators along with
examples and results.

Figure 5.1 – Arithmetic Operators


Figure 5.2 – Increment/Decrement Operators

Assignment, Comparison, and Logical Operators


Figure 5.3, Figure 5.4 and Figure 5.5 shows the assignment, comparison, and logical operators along with
examples.

Figure 5.3 – Assignment Operators

Figure 5.4 – Comparison Operators

Figure 5.5 – Logical Operators


PHP CONDITIONALS

Conditionals alter program flow. These enables you to ask questions about certain things and respond to
the answers you get in different ways. Conditionals are central to dynamic web pages—the goal of using
PHP in the first place—because they make it easy to create different output each time a page is viewed.
There are three types of non-looping conditionals: the if statement, the switch statement, and the ?
Operator. By non-looping, it means that the actions initiated by the statement take place and program
flow then moves on, whereas looping conditionals execute code over and over until a condition has
been met.

Simple Decisions with if Statement


The easiest decision making statement to understand is the if statement. It basic form is:

Syntax: Example:

 if ( expression ) {
// Run this code
}
 // More code here

If the expression inside the parentheses evaluates to true, the code between the braces is run. If the
expression evaluates to false, the code between the braces is skipped.

Providing Alternate Decisions with if-else Statement


The if statement allows you to run a block of code if an expression evaluates to true. If the expression
evaluates to false, the code is skipped. This process can be enhanced by adding an else statement to an
if construction. This lets you run one block of code if an expression is true, and a different block of code
if the expression is false.

Syntax: Example 1: Example 2:

 if ( expression ) {
// Run this code
}
else {
// Run another code
}
Example 5: Use of Multiple-line if… elseif… Statements

1. <?php
2. if ($page == "Home") echo "You selected Home";
3. elseif ($page == "About") echo "You selected About";
4. elseif ($page == "News") echo "You selected News";
5. elseif ($page == "Login") echo "You selected Login";
6. elseif ($page == "Links") echo "You selected Links";
7. ?>

Testing One Expressions Many Times with Switch Statements


Sometimes you want to test an expression against a range of different values, carrying out a different
task depending on the value that is matched. This can be achieved using the switch statements.

Example 6: Use of Switch Statement

1. <?php
2. switch ($page)
3. {
4. case "Home":
5. echo "You selected Home";
6. break;
7. case "About":
8. echo "You selected About";
9. break;
10. case "News":
11. echo "You selected News";
12. break;
13. case "Login":
14. echo "You selected Login";
15. break;
16. case "Links":
17. echo "You selected Links";
18. break;
19. }
20. ?>

The ? Operator
The ? operator is passed an expression that it must evaluate, along with two statements to execute: one
for when the expression evaluates to TRUE, the other for when it is FALSE. Example 7 shows sample use
of ? operator.
Example 7: Use of ? Operator

1. <?php
2. echo $fuel <= 1 ? "Fill tank now" : "There's enough fuel";
3. ?>

PHP LOOPS

Looping makes scripts more powerful and useful. The basic idea of a loop is to run the same block of
code again and again, until a certain condition is met. As with decisions, that condition must take the
form of an expression. If the expression evaluates to true, the loop continues running. If the expression
evaluates to false, the loop exits, and execution continues on the first line following the loop’s code
block.

while Loop
The simplest type of loop to understand uses the while statement. Its syntax is as follows:

 initialization;
 while ( expression ) {
// increment/decrement
// Run this code
}
 // More code here

Here’s how it works. The expression inside the parentheses is tested; if it evaluates to true, the code
block inside the braces is run. Then the expression is tested again; if it’s still true, the code block is run
again, and so on. However, if at any point the expression is false, the loop exits and execution continues
with the line after the closing brace. Here’s a simple, practical example of a while loop:

Example 8: while Loop

1. < ?php
2. $widgetsLeft = 10;
3. while ( $widgetsLeft > 0 ) {
4. echo “Selling a widget... “;
5. $widgetsLeft - - ;
6. echo “done. There are $widgetsLeft widgets left. < br / > ”;
7. }
8. echo “We ’ re right out of widgets!”;
9. ? >

In this example, first a variable $widgetsLeft is created to record the number of widgets in stock (10).
Then the while loop works through the widgets, “selling” them one at a time (represented by
decrementing the $widgetsLeft counter) and displaying the number of widgets remaining. Once
$widgetsLeft reaches 0, the expression inside the parentheses ( $widgetsLeft > 0 ) becomes false , and
the loop exits. Control is then passed to the echo() statement outside the loop, and the message “ We’re
right out of widgets! ” is displayed.

foreach Loop
foreach is a special kind of looping statement that works only on arrays (and objects). It is used in two
ways: One to either retrieve just the value of each element, or to retrieve the element’s key and value.

The simplest way to use foreach is to retrieve each element’s value, as follows:

 foreach ( $array as $value ) {


// (do something with $value here)
}
 // (rest of script here)

As you might imagine, the foreach loop continues to iterate until it has retrieved all the values in the
array, from the first element to the last. On each pass through the loop, the $value variable gets set to
the value of the current element. You can then do whatever you need to do with the value within the
loop’s code block. Then, the loop repeats again, getting the next value in the array, and so on. Here’s an
example:

Example 9: Using foreach to Loop through Values

1. < ?php
2. $authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
3. foreach ( $authors as $val ) {
4. echo $val . “ < br/ > ”;
5. }
6. ? >

To use foreach to retrieve both keys and values, use the following syntax:

 foreach ( $array as $key = > $value ) {


// (do something with $key and/or $value here
}
 // (rest of script here)

This behaves exactly like the previous foreach construct; the only difference is that the element’s key is
also stored in the $key variable. (Again, you can use any variable names you like; they don’t have to be
$key and $value.)

Example 10: Using foreach to Loop through Keys and Values


1. < ?php
2. $myBook = array( “title” = > “The Grapes of Wrath”,
3. “author” = > “John Steinbeck”,
4. “pubYear” = > 1939 );
5. foreach ( $myBook as $key = > $value ) {
6. echo “ < dt > $key < /dt > ”;
7. echo “ < dd > $value < /dd > ”;
8. }
9. ? >

do-while Loop
A slight variation to the while loop is the do ... while loop. It is used when you want a block of code to be
executed at least once before checking the expression. Its syntax is as follows:

 initialization;
 do {
// increment/decrement
// Run this code
} while ( expression );
 // More code here

Here’s a simple, practical example of a do-while loop:

Example 11: do-while Loop

1. < ?php
2. $width = 1;
3. $length = 1;
4. do {
5. $width++;
6. $length++;
7. $area = $width * $length;
8. } while ( $area < 1000 );
9. echo “The smallest square over 1000 sq ft in area is $width ft x $length ft.”;
10. ? >

This example computes the width and height (in whole feet) of the smallest square over 1000 square
feet in area (which happens to be 32 feet by 32 feet). It initializes two variables, $width and $height,
then applies a do...while loop to increment these variables and compute the area of the resulting
square, which it stores in $area variable. Because the loop is always run at least once, you can be sure
that $area will have a value by the time it’s checked at the end of the loop. If the area is still less than
1000, the expression evaluates to true and the loop repeats.
for Loop
The final kind of loop statement, the for loop, is also the most powerful, as it combines the abilities to
set up variables as you enter the loop, test for conditions while iterating loops, and modify variables
after each iteration.

Typically, you use a for loop when you know how many times you want to repeat the loop. You use a
counter variable within the for loop to keep track of how many times you’ve looped. The general syntax
of a for loop is as follows:

 for ( initialization expressions; condition expression; modification expressions ) {


// Run this code
}
 // More code here

Here’s a simple, practical example of a for loop:

Example 12: for Loop

1. <?php
2. for ($count = 1 ; $count <= 12 ; ++$count)
3. echo "$count times 12 is " . $count * 12 . "<br>";
4. ?>

This example prints the table of 2 using for loop. At the start of the first iteration of the loop, the
initialization expression is executed. $count is initialized to the value 1. Then, each time around the loop,
the condition expression (in this case, $count <= 12) is tested, and the loop is entered only if the
condition is TRUE. Finally, at the end of each iteration, the modification expression is executed. Here,
the variable $count is incremented.

---------------------------Task 5.3---------------------------
Write PHP script that shows the division table displayed as in Table 5.2 using different loops.
For each number, display whether that number is an odd or even number, and also display a
message if the number is a prime number. Display this information within an HTML table.

---------------------------Task 5.4---------------------------
Explore PHP Object Oriented using examples showing classes, objects, inheritance, and
polymorphism.

---------------------------Task 5.5---------------------------
Build an image gallery website using PHP without database. Your website must show all the
images in a given directory. Use bootstrap/CSS in your website. Please note that when a given
image is clicked, it enlarges it and shows in higher resolution. Also, your website should be
flexible enough to show the images when number of images are increased or decreased from a
given directory.

Table 5.2 – Division Table for Task 5.3

---------------------------Task 5.6---------------------------
Tutorial on PHP MVC Framework: LARAVEL.

a) Install Composer: https://getcomposer.org/download/


b) composer create-project --prefer-dist laravel/laravel testProject
c)

d)

e) Now press CTRL+C to exit.

f)

g)
h) Press Home.

i) Press Register.
j) Next create new database in MySQL:

k) Next open .env file.

l) Perform the following changes in .env file and save the file.
m) Next press CTRL+C in CMD and type php artisan migrate. Press Enter. This will create
tables in testProject database created earlier.

n) Run the server as shown in step g. Register a new user.


o) Click Sumayyea/Your name to logout. Now Login for Sumayyea/Your Name.
---------------------------Task 5.7---------------------------
Implement the following relationship in Laravel.

Department: depID, depName


Emplyee: empID, empName, empJob, dID

Note that the department has at least one or many employees working in it; while employee
works exactly in one department. Also, feed atleast five records in the created tables.

You might also like