8169 PHP 2019 Onwards
8169 PHP 2019 Onwards
(Pages:4) N-8169
Reg. No.
Name
Core Course
SECTION- A
Very Short Answer Type. One word to maximum of one sentence. Answer all
questions.
1 or is used to display output in PHP.
P.T.O.
7. The information sent from an HTML form using the method is
visible to everyone in the browser's address bar.
(6x 4 24 Marks)
3
N-8169
SECTION- D
Long Essay. Answer any two questions. Each question carries 15 marks.
(b) $_GET
41. Discuss various loops used in PHP.
42. Write a PHP script to fetch and display the records stored in MySQL.
N-8169
à ( 44 PaUa
iNsw Kuy
Remarks on Scrutiny
No. of pages
Page No.
Ndlia NP
hoUndrom CA
ANSWER KEY
CS 1444/CP 1443 PHP and MYSQL
(2018 Admission onwards)
Time 3 Hours
Maximum Marks: 80
Page 1 of 10
18. An open source database has code that is open and free for download, modification and re-use.
This is the opposite of a proprietary or closed source database in which the code is protected to
prevent copying.
19. fread() -Read the file's content using fread() function. A new file can be written or text can be
appended to an existing file using the PHP fwritc() function.
20. S GET,S POST, S REQUEST, S SESsSION, $_COOKIE, $_FILES (Any 4)
21 <?php
$servername = "locallhost"
Susername = "username";
Spassword= "password",
Sdbname= "myDB",
/ Create connection
Sconn new mysqli(Sservername, Susername, Spassword, Sdbname
/ Check connection
if(Sconn->connect_error){
die("Connection failed:".Sconn->connect_error);
// sql to delete a table
Ssql = "DELETE FROM EMPLOYEE";
if(Sconn->query(Ssql)=TRUE) {
echo "Record deletedsuccessfully"
else {
echo "Error deleting record: ". Sconn->error;
Sconn->close();
AND, OR, and NOT
FLOAT(M,D)- This is a floating-point number that cannot be unsigned. We can define the display
length (M) and the number of decimals (D). This is not required and will default to 10,2, where 2
is the number of decimals and 10 is the total number of digits (including decimals). Decimal
precision can go to 24 places for a FLOAT. DOUBLE(M,D) - A double precision floating-point
number that cannot be unsigned. We can define the display length (M) and the number of decimals
(D). This is not required and will default to 16,4, where 4 is the number of decimals. Decimal
precision can go to 53 places for a DOUBLE.
Open Source, Scalable, Variety of data types, variety of character sets, secure, support for large
24
databases, client and utility programs(Any 4)
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There
25 are two wildcards often used in conjunction with the LIKE operator: The percent sign (%)
represents zero, one, or multiple characters. The underscore sign represents one, single
character.
The INNER JOIN keyword selects records that have matching values in both tables. INNER JOIN
26
Syntax SELECT column_name(s) FROM tablel INNER JOIN table2 ON tablel.column_name
= table2.column_name,
Page 2 of 10
27. A variable starts with the $ sign, followed by the name of the variable. A variable name must start
with a letter or the underscore character. A variable name cannot start with a number. A variable
name can only contain alpha-numeric characters and underscores (A-z, 0-9, and_). Variable
names are case-sensitive (Ssum and $SUM are two different variables).
28. The PHP break keyword is used to terminate the execution of a loop prematurely. The break
statement is situated inside the statement block. It gives us full control and whenever we want to
exit from the loop we can come out. After coming out of a loop immediate statement to the loop
will be executed.
Example Program
<?php
$x=1;
while(Sx <=5) {
echo "The number is: $x <br>"
Sx++;
if Sx-3) break;
echo "Executed the break"
Output
The number is: 1
The number is: 2
Executed the break
continue Statement
it does not terminate
The PHP continue keyword is used to halt the current iteration of a loop but
inside the statement block
the loop. Just like the break statement the continue statement is situated
a conditional test. For the pass
containing the code that the loop executes, preceded by
and next pass starts.
encountering continue statement, rest of the loop code is skipped
Example Program
<?php
Sx= 1,
while($x <=5) {
Sx++;
if(Sx=3) continue;
echo "The number is: Sx <br>";,
start with a letter or underscore but not a number. In PHP, function names
A function name can
Page 3 of 10
Example Program
<html>
head>
titleWriting PHP Function with Parameters-/itle
</head>
<body>
?php
function addFunction(Sa, Sb) {|
Ssum S a + Sb;
echo "Sum of the two numbers is: Ssum",
addFunction(100, 200);
<body>
</html>
about the current date and time.
30. PHP's time() function gives you all the information that you need
the number
It requires no arguments but returns an integer. The integer returned by time() represents
moment is known as the UNIX
of seconds elapsed since midnight GMT on January 1, 1970. This
then is referred to as a time stamp.
epoch, and the number of seconds that have elapsed since
31. The function getdate() optionally accepts a time stamp and returns an associative array containing
current time stamp as
information about the date. If you omit the time stamp, it works with the
returned by getdate(). 1
returned by time(). Following are the elements contained in the array
3.hours-
seconds Seconds past the minutes (0-59). 2 minutes -Minutes past the hour (0 - 59).
month (1 31). 5 wday Day of the week (0 6). 6
of the
-
9
mon - Month of the year (1 12). 7 year - Year (4 digits) 8. yday Day of year (0-365 ).
-
persistent we must provide it with an expiration time. Then the cookie will only expire after the
given expiration time, until then it will be a valid cookie.
33. The user opens the page containing a HTML form featuring a text files, a browse button and a
submit button. The user clicks the browse button and selects a tile to upload from the local PC. The
full path to the selected file appears in the text filed then the user clicks the submit button. The
selected file is sent to the temporary directory on the server. The PHP script that was specitied as
the form handler in the form's action attribute checks that the file has arrived and then copies the
file into an intended directory. The PHP script confirms the success to the user.
34. The include() function takes all the text in a specified file and copies it into the file that uses the
include function. If there is any problem in loading a file then the include() function generates a
warning but the script will continue execution. Including files saves a lot of work. This means that
we can create a standard header, footer, or menu file for all our Webpages. Then, when the header
needs to be updated, we can only update the header include file.
35 There is one global PHP variable called $ FILES. This variable is an associate double dimension
array and keeps all the information related to uploaded file. So if the value assigned to the input's
Page 4 of 10
name attribute in uploading form was file, then PHP would create following five variables
FILESSile][ tmp_ name'] - the uploaded file in the temporary directory on the web server.
the size in
Sbytes
FILESfile ]Tname']
of the uploaded
-
36. PHP S_REQUEST is used to collect data after submitting an HTML form. The PHP S_REQUEST
variable contains the contents of both $_GET, S_POST and S_COOKIE. The PHP SREQUEST
variable can be used to get the result from form data sent with both the GET and POST methods.
37. asort()- Sort associative arrays in ascending order, according to the value. ksort()- Sort associative
arrays in ascending order, according to the key.
38. PHP makes use of mail() function to send an email. This function requires three mandatory
arguments that specify the recipient's email address, the subject of the message and the actual
message additionally there are other two optional parameters. mail( to, subject, message, headers,
parameters); to - Required. Specifies the receiver/ receivers of the email, subject - Required.
Specifies the subject of the email. This parameter cannot contain any newline characters. Message
- Required. Defines the message to be sent. Each line should be separated with a LF (n). Lines
should notexceed70 characters. Headers-Optional. Specifies additional headers, like From, Ce,
andBcc. Parameters Optional. Specifies an additional parameter to the send mail program. As
soon as the mail function is called PHP will attempt to send the email then it will return true if
successful or false if it is failed. Multiple recipients can be specified as the first argument to the
mail() function in a comma separated list.
integer: They are whole numbers, without a decimal point, like 235. They are the
and they correspond to simple whole simplest type
numbers, both positive and negative. Integers can be assigned
to variables, or they can be used in
expressions. Integer can be in decimal
8), and hexadecimal (base 16) format. Decimal format is the default, octal (base 10), octal (base
with a leading 0, and hexadecimals have a integers are specified
leading 0x. An integer data
number between -2,147,483,648 and 2,147,483,647. float: A float type is anon-decimal
number with a decimal point or a number in (floating point number) iss a
exponential
minimum number of decimal places needed. boolean:
form. By default, float prints with the
true or false. PHP
They have only two possible values either
provides a couple of constants especially for use as Booleans: TRUE and
FALSE. string: They are sequences of characters.
There are no limits on string
on the bounds of available length. It depends
memory. We can use both single quoted and double
Compound Types -There are 2 compound data types in PHP. quoted strings.
array: An stores multiple
values in one
single variable. An array can be declared as array follows. Sfruits
array('apple","orange",
=
"grapes"), object:
information on how to process that data. In
An object is a data
type which stores data and
PHP, an object must be explicitly declared. First we
Page 5 of 10
must declarea class of object. For this, we use the class keyword. A class is a structure that can
contain properties and methods. There are 2 special data types in PHP resource: The special
resource type is not an actual data type. It is the storing of a reference to functions and resources
external to PHP. A common example of using the resource data type is a database call. NULL:
Null is a special data type which can have only one value NULL. A variable of data type NULL is
a variable that has no value assigned to it. Ifa variable is created without a value, it is automatically
assigned a value of NULL. Variables can also be emptied by setting the value to NULL. The NULL
value can be assigned as follows. Sx=null;
40. a) Cookie management- A cookie is a small file with the maximum size of 4KB that the Web server stores
on the client computer. Once a cookie has been set, all page requests that follow return the cookie name
and value. A cookie can only be read from the domain that it has been issued from. For example, a cookie
set using the domain www.example.com cannot be read from the domain career.example.com. A cookie
created by a user can only be visible to them. Other users cannot see its value. Most Web browsers have
options for disabling cookies, third party cookies or both. If this is the case then PHP responds by passing
the cookie token in the URL. Cookies allow us to track the state of application using small files stored on
the user's computer. The path were the cookies are stored depends on the browser. Following is the basic
syntax used to create a cookie.
<?php
setcookie (cookie_name, cookie_value, [expiry_time], [ cookie_path], (domain],
secure], [httponly]);
All parameters except cookie name and cookie value are optional. setcookie is the
PHP function used to create the cookie.
cookie name is the
will use when retrieving its value from the
of the cookie that the server
name
$_COOKIE array variable. It's mandatory.
cookie_value is the value of the cookie and its mandatory. expiry_time is optional. It can
be used to set the expiry time for the cookie
such as 1 hour. The time is set
functions plus or minus a number of seconds using the PHP time(0
greater than 0 i.e. time() + 3600 for 1 hour.
cookie_path is optional. It can be used to set the cookie path on the server. The forward slash
means that the cookie will be made available on the
entire domain. Sub directories limit the
cookie access to the subdomain. Domain is
hierarchy i.e.
optional, it can be used to define the cookie access
www.cookiedomain.com means entire domain while
limits the cookie access to www.sub.cookiedomain.com
www.sub.cookiedomain.com and its sub domains.
a subdomain of asubdomain as long as the total It's possible to have
characters do not
is optional, the default is false. It is used to determine whether theexceed 253 characters. Secure
set to true or http if it is set to cookie is sent via https if it is
false. Httponly is
scripting languages can access them i.e. optional. If it is set to true, then
only client side
Example Program JavaScript cannot access them.
<?php
setcookie ("user_name", "99", time ()+ 60,'/'); //
echo 'the cookie has
been set for 60
expires after 60 seconds
b) S_GET- The GET method sends the encoded user seconds' ;:?>
The page and the encoded infomation appended to the
information are separated by the ?
character. The GET method request.
page
a
long string that appears in our server
to send upto 1024 logs, in the browser's location. The GET method produces
characters only. Never use GET is restricted
information to be sent to the server. method if we have
password or other sensitive
documents, to the server. The data sentGET can't be used to send binary data, like images or word
environment variable. The PHP by GET method can be accessed
using QUERY_STRING
information using GET method. provides S_GET associative array to acess all the sent
Example Program
<?php
if( $_GET [ "name"] || $_GET["age"]
echo "Welcome". $GET ['name']. "<br />"
echo "You are ". $_GETI'age']. " years old, ";
exit ();
<html>
body> "GET">
method
?>" =
form action =
"< ?php $ PHP SELF
"text" name= "name" />
Name: <input type =
</form>
</body>>
</html>>
Output
Submit
Name Age
to everyone (all variable names and
Information sent from a form with the GET method is visible
amount of information to send. GET
values are displayed in the URL). GET also has limits on the
non-sensitive data. GET should never be used for sending passwords
or
may be used for sending
other sensitive information.
PHP supports following four loop types: for loop, while loop, do..while loop and foreach loop
41. statement or
want to execute a
for Loop The for loop is used when we know how many times
-
we
where the initialization initialize the loop counter value, condition is evaluated for each loop
the loop ends. The
iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE,
increment increases/decreases the loop counter value.
is true.
while Loop - The while loop will execute a block of code if and as long as a test expression
If the test expression is true then the code block will be executed. After the code has executed the
test expression will again be evaluated and the loop will continue until the test expression is found
to be false. Following is the syntax of while loop.
while (condition) {
code to be executed,
do..while Loop - The do..while loop will execute a block of code at least once - it will then repeat
the loop as long as a condition is true. The syntax of do..while loop is as follows.
do{
code to be executed;
while (condition);
foreach Loop - The foreach loop is used to loop through arrays. For each pass, the value of the
current array element is assigned to Svalue and the array pointer is moved by one and in the next
pass, next element will be processed. The syntax of foreach loop is as follows.
Page 7 of 10
foreach (amray as value)
code to be executed;
42 php
$dbhost "localhost
Sdbuser 'root'
Sdbpass"
Sdb-"TESTDB';
/ Create connection
Sconn =mysqli_connect(Sdbhost, Sdbuser, Sdbpass,$db);
I/ Check connection
if(Sconn->connect_error) {
die("Connection failed: ".Sconn->connect_error);
Srow["emp_salary"]. "<br>";
else{
echo "0 results";
A session is a global variable stored on the server. Each session is assigned a unique
id which is
43 used to retrieve stored values. Whenever a session is created, a cookie containing the unique session
id is stored on the user's computer and returned with every request to the server. If the client
browser does not support cookies, the unique php session id is displayed in the URL. Sessions have
the capacity to store relatively large data compared to cookies. The session values are automatically
deleted when the browser is closed. If we want to store the values permanently, then we should
store them in the database. Just like the $_C0OKIE array variable, session variables are stored in
the S_SESSION array variable. Just like cookies, the session must be started before any HTML
tags. We want to store important information such as the user id more securely on the server where
malicious users cannot temper with them. Sometimes we want to pass values from one page to
another. There may be situations where we want the alternative to cookies on browsers that do not
support cookies. In some case, we want to store global variables in an efficient and more secure
Page 8 of 10
an application such
compared to passing them in the URL. They are useful while developing
way than 4KB. In order
as a shopping cart that has to temporary
store information with a capacity larger
the
function and then store our values in
session, we must first call the PHPsession start
to create a has
we want to know the
number of times that a page
S SESSION array variable. Let's suppose retrieve
create and
been loaded, we can use a session to do that.
The code below shows how to
variable is already set
function to checkifsession
values from sessions. We can make use of isset()
or not.
Example Program 1
php
the PHP_session function
session_start(); /start
ifisset($_SESSION[ page_count]))
SSESSION[page_count| +=1;
else
S_SESSION[ page_count]= 1;
php session
session_destroy(); //destroy entire
Example Program 2
Page 9 of 10
</head>
<body>
<?php
/ Method to create an Associative Array
echo "First Method for Associative Array Creation<br",
Ssalary-array("Smith"=>"550000","Johns"->"250000","Adam"=>"200000")
body>
</html> element in the main array can also
Multidimensional Arrays -
In a multi-dimensional array, each
can be an array and so on.
Values in the multi-
be an array. And each element in the sub-array multidimensional arrays
indices. PHP understands
dimensional array are accessed using multiple
three levels deep
levels deep. However, arrays more than
that are two, three, four, five, or more known as array of arrays.
are hard to manage for most people.
PHP multidimensional array is also
in the
PHP multidinmensional array can be represented
It allows us to store tabular data in an array. * how to create
column. Following program illustrates
form of matrix which is represented by row
access its elements.
a two dimensional aray and
Example Program
<html>
<head
stitle>Multidimensional Arrays</title>
</head>
<body>
<Iphp array(3,"Adam",300000):
Semp-array ( array(1,"Smith",400000), array(2,"Johns",500000),
echo Semp[O][0].".Name: ".Semp[O][1].", Salary: ".Semp[O][2]."<br>";
echo Semp[1][0]."Name: "Semp[1][1].", Salary: ".Semp[1][2]"<br>":
echo Sempl2][0]."Name: "Semp[2][1]", Salary: ".Semp[2]|2]"<br";
</body>
</html>
Page 10 of 10