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

Expected Question and Their Answers by Ritesh of php

The document contains a series of PHP-related questions and answers, covering topics such as cookie management, session variables, database operations, and form handling. It provides code examples for various operations like creating sessions, using GET and POST methods, and validating user inputs. Additionally, it includes explanations of PHP functions like mail and how to create a PDF document.

Uploaded by

riteshdebadwar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Expected Question and Their Answers by Ritesh of php

The document contains a series of PHP-related questions and answers, covering topics such as cookie management, session variables, database operations, and form handling. It provides code examples for various operations like creating sessions, using GET and POST methods, and validating user inputs. Additionally, it includes explanations of PHP functions like mail and how to create a PDF document.

Uploaded by

riteshdebadwar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Expected Question and Their Answers by Ritesh

of php

2 marks question and answers


Q.1) How we can destroy cookies
Ans: We can destroy the cookie just by updating the expire-
time value
of the cookie by setting it to a past time using the
setcookie() function.
Syntax: setcookie(name, time() - 3600);

Q.2) List any 4 data types in MYSQL


Ans: CHAR
VARCHAR
INT(m)/
INTEGER(
m)
DATE() (3 bytes)
DATETIME()
Q.3) how to create session variables in php
Ans: Session variable can be set with a help of a PHP global
variable:
$_SESSION.
Data in the session is stored in the form of keys and values
pair.
We can store any type of data on the server, which include
arrays and objects.
Ex:
<?php
session_start();
$_SESSION["username"] = "abc";
?>

Q.4) state role of GET and POST methods


Ans: i)Get method:
It processes the client request which is sent by the client,
using the
HTTP get method.Browser uses get method to send request.
ii)Post method
It Handles request in servlet which is sent by the client. If a
client is
entering registration data in an html form, the data can be
sent using
post method.

Q.5) List two database operations.


Ans:
1.mysqli_affected_rows()
2. mysqli_close()
3. mysqli_connect()
4. mysqli_fetch_array()
5.mysqli_fetch_assoc()
6.mysqli_affected_rows()
7. mysqli_error()

Q.6) State the use of cookies.


Ans:
Cookie is used to keep track of information such as a
username that
the site can retrieve to personalize the page when the user
visits the
website next time.
Q.7) Write syntax of constructing PHP webpage with MySQL
Ans. Using MySQLi object-oriented procedure:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername, $username, $password);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Q.8) Enlist the attributes of cookies.
Ans. Attributes of Cookies are as follows: List any four
1. name attributes
2. value each
3. expire
4. path
5. domain
6. secure
Q.9) Define session and cookies
Ans:
Cookies
Cookies are small pieces of data stored on the user's
browser by the web server. They help remember information
across different visits to the same website.

setcookie("username", "ritesh", time() + 3600); // 1 hour


echo $_COOKIE["username"];

Session
A session is a way to store data on the server for individual
users. It helps track users and their data while they navigate
across multiple pages of a website.
<?
session_start();

$_SESSION["username"] = "ritesh";
echo $_SESSION["username"];
?>
Q.10) List types of MYSQL storage engine
Ans: 1)MYISAM
2)InnoDB
3)MEMORY
4)MERGE
5)EXAMPLE
6)ARCHIEVE

Q.11)List different types superglobal variables


Ans: 1)$_SERVER
2) $_REQUEST
3)$_GET
4)$_POST
5)$_COOKIE
6)$_SESSION
7)$_FILES
4 mark question and answers
Q.1) Write difference between get() and post() method of
form
Ans:

Feature GET POST

Sends data via


Purpose Sends data via URL HTTP request
body

Data is not visible


Visibility Data is visible in the URL
in the URL

Less secure (data can be More secure (data


Security
seen/bookmarked) not shown in URL)

No size limit for


Data Length Limited (URL length limit)
data

Caching Can be cached Cannot be cached

URL with data can be Cannot bookmark


Bookmarking
bookmarked form data
Feature GET POST

Use for login,


Use for searching, filters,
Usage forms, sensitive
queries
data

Q.2) Write difference between session and cookie


Ans:

Feature Session Cookie

Storage Stored on client-side


Stored on server-side
Location (browser)

More secure (not Less secure (user can


Security
visible to user) view/edit in browser)

Can store large


Data Size Limited to about 4KB
amounts of data

Ends when browser is Can be set to expire at


Lifetime
closed (by default) a specific time

Accessed via $_SESSION Accessed via $_COOKIE


Access
in PHP in PHP
Feature Session Cookie

Best for storing


Best for storing
Usage preferences, remember
sensitive/user info
me

Login details during a Save theme choice or


Example
session username

Q.3) Explain delete operation of php on table data


Ans:
The DELETE operation in PHP is used to remove records
from a table in a database (usually MySQL).
Delete command is used to delete rows that are no longer
required
from the database tables. It deletes the whole row from the
table.

The DELETE statement is used to delete records from a table:


DELETE FROM table_name WHERE some_column =
some_value
[WHERE condition] is optional. The WHERE clause specifies
which record or records that should be deleted. If the WHERE
clause is not used, all records will be deleted.
Below is a simple example to delete records into the
student.pridata
table. To delete a record in any table it is required to locate
that
record by using a conditional clause.

Ex:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "your_database_name";

$conn = new mysqli($servername, $username, $password,


$database);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "DELETE FROM students WHERE id = $id";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully.";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>

Q.4) Explain inserting and retrieving the query result


operations.
Ans:
INSERT Operation in PHP
<?php
$conn = new mysqli("localhost", "root", "",
"your_database_name");

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$name = $_POST['name'];
$email = $_POST['email'];

$sql = "INSERT INTO students (name, email) VALUES ('$name',


'$email')";

if ($conn->query($sql) === TRUE) {


echo "Record inserted successfully.";
} else {
echo "Error: " . $conn->error;
}

$conn->close();
?>

RETRIEVE Operation in PHP


Ex:
<?php
$conn = new mysqli("localhost", "root", "",
"your_database_name");

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, name, email FROM students";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo "<table border='1'>
<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['email']}</td>
</tr>";
}
echo "</table>";
} else {
echo "No data found.";
}

$conn->close();
?>

Q.5) create customer form like customer name, address,


mobile no , date of birth using different form of input and
display user inserted values In new php form
Ans:
Html form
<!DOCTYPE html>
<html>
<head>
<title>Customer Form</title>
</head>
<body>
<h2>Customer Details</h2>
<form action="display_customer.php" method="post">
<label for="name">Customer Name:</label><br>
<input type="text" name="name" required><br><br>

<label for="address">Address:</label><br>
<textarea name="address" rows="4" cols="30"
required></textarea><br><br>

<label for="mobile">Mobile No:</label><br>


<input type="tel" name="mobile" pattern="[0-9]{10}"
required><br><br>

<label for="dob">Date of Birth:</label><br>


<input type="date" name="dob" required><br><br>

<input type="submit" value="Submit">


</form>
</body>
</html>

Php form
<?php
echo "<h2>Customer Details Submitted</h2>";

$name = $_POST['name'];
$address = $_POST['address'];
$mobile = $_POST['mobile'];
$dob = $_POST['dob'];

echo "Name: " . htmlspecialchars($name) . "<br>";


echo "Address: " . nl2br(htmlspecialchars($address)) . "<br>";
echo "Mobile No: " . htmlspecialchars($mobile) . "<br>";
echo "Date of Birth: " . htmlspecialchars($dob) . "<br>";
?>

Q.6) Explain mail function in php with example


Ans:
1. PHP mail is the built-in PHP function that is used to send
emails from PHP Correct
2. The mail function accepts the following parameters;
a) Email address
b) Subject
c) Message
d) CC or BCC email addresses
3. The PHP mail function has the following basic syntax
<?php
mail($to_email_address,$subject,$message,[$headers],[$par
ameters]);
?>
HERE,
a) “$to_email_address” is the email address of the mail
recipient
b) “$subject” is the email subject
c) “$message” is the message to be sent.
d) “[$headers]” is optional, it can be used to include
information such as
CC, BCC
CC is the acronym for carbon copy. It s used when you want
to send a ‟
copy to an interested person i.e. a complaint email sent to a
company can
also be sent as CC to the complaints board.
BCC is the acronym for blind carbon copy. It is similar to CC.
The email
addresses included in the BCC section will not be shown to
the other
recipients.
4. PHP mailer uses Simple Mail Transmission Protocol (SMTP)
to send mail.
On a hosted server, the SMTP settings would have already
been set. The
SMTP mail settings can be configured from “php.ini” &
“sendemail.ini”
file in the PHP installation folder.
Php Mail Example
<?php
$to_email = 'name @ company . com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply @ company . com';
mail($to_email,$subject,$message,$headers);
?>

Q.7) Write a PHP program to demonstrate use of cookies.


Ans:
Cookies can be used to identify user, managing session, etc.
Setting cookies for human identification:
In the code below, two fields name and year are set as
cookies on user's machine. From the two fields, name field
can be used to
identify the user's revisit to the web site.
<?php
setcookie("name", "WBP", time()+3600, "/","", 0);
setcookie("Year", "3", time()+3600, "/", "", 0);
?>
For the first time when user visits the web site, cookies are
stored
on user's machine. Next time when user visits the same page,
cookies from the user's machine are retrieved.
In the code below isset() function is used to check if a cookie
is set
or not on the user's machine.
<html>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . " Thanks for
Revisiting"."<br />";
else
echo "First Time Visitor". "<br />";
?>
</body>
</html>

Q.8)Write a program to create pdf document in PHP


Ans. <?php
require("fpdf/fpdf.php");
$pdf = new FPDF();
$pdf->addPage();
$pdf->setFont("Arial", 'IBU', 16);
$pdf->settextcolor(150,200,225);
$pdf->cell(40, 10, "Hello Out There!");
$pdf->output();
?>
Q.9) How do you validate user inputs in PHP.
Ans:
Invalid user input can make errors in processing.
Therefore,
validating inputs is a must.
1. Required field will check whether the field is filled or not in
the
proper way. Most of cases we will use the * symbol for
required
field.
2. Validation means check the input submitted by the user.

There are two types of validation available in PHP.


Client-Side Validation − Validation is performed on the client
machine web browsers.
Server Side Validation − After submitted by data, The data is
sent to a server and performs validation checks in the server
machine.
Some of Validation rules for field
Field Validation Rules
Name Should required letters and white-spaces
Email Should be required @ and .
Website Should required a valid URL
Radio Must be selectable at least once
Check Box Must be checkable at least once
Drop Down menu Must be selectable at least once
The preg_match() function searches a string for pattern,
returning
true if the pattern exists, and false otherwise.
To check whether an email address is well-formed is to use
PHP's
filter_var() function.
empty() function will ensure that text field is not blank it is
with
some data, function accepts a variable as an argument and
returns
TRUE when the text field is submitted with empty string, zero,
NULL or FALSE value.
Is_numeric()
function will ensure that data entered in a text field is
a numeric value, the function accepts a variable as an
argument and
returns TRUE when the text field is submitted with numeric
value.
Ex:
<!DOCTYPE html>
<body>
<?php
$nerror = $merror = $perror = $werror = $cerror = "";
$name = $email = $phone = $website = $comment = "";
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)* @[a-z0-9-]+(\.[a-z0-9-
]+)*(\.[a-z]{2,3})$^";

if($_SERVER["REQUEST_METHOD"]=="POST") {
if(empty($_POST["name"])) {
$nerror = "Name cannot be empty!";
}
else {
$name = test_input($_POST["name"]);
if(!preg_match("/^[a-zA-Z-']*$/",$name))
{
$nerror = "Only characters and white spaces allowed";
}
}
if(empty($_POST["email"])) {
$merror = "Email cannot be empty!";
}
else
{
$email = test_input($_POST["email"]);
if(!preg_match($pattern, $email)) {
$merror = "Email is not valid";
}
}
if(empty($_POST["phone"])) {
$perror = "Phone no cannot be empty!";
}
else {
$phone = test_input($_POST["phone"]);
if (!preg_match ('/^[0-9]{10}+$/', $phone)) {
$perror = "Phn no is not valid";
}
}
if(empty($_POST["website"])) {
$werror = "This field cannot be empty!";
}
else {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$werror = "URL is not valid";
}
}
if (empty($_POST["comment"])) {
$cerror = "";
}
else {
$comment = test_input($_POST["comment"]);
}}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p><span class="error">* required field </span></p>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo
$nerror;?></span><br/><br/>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo
$merror;?></span><br/><br/>
Phone no: <input type="text" name="phone">
<span class="error">* <?php echo
$perror;?></span><br/><br/>
Website: <input type="text" name="website">
<span class="error">* <?php echo
$werror;?></span><br/><br/>
Comment: <textarea name="comment" rows="5"
cols="40"></textarea><br/><br/>
<input type="submit" name="submit"
value="Submit"></form>
<?php
echo "<h2>Your Input:</h2>";
echo $name; echo "<br>";
echo $email; echo "<br>";
echo $phone; echo "<br>";
echo $website; echo "<br>";
echo $comment;
?>
</body>
</html>
Q.10) How do you connect MYSQL database with PHP
Ans:
Using MySQLi Object Interface:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
mysqli_close($conn);
?>
Explanation:
The first part of the script is three variables (server name,
username, and password) and their respective values. These
values
should correspond to your connection details. Next is the
main PHP function mysqli_connect(). It establishes a
connection with the specified database.
When the connection fails, it gives the message Connection
failed.
The die function prints the message and then exits out of the
script
If the connection is successful, it displays “Connected
successfully.” When the script ends, the connection with the
database also closes. If you want to end the code manually,
use
the mysqli_close function.

Q.11) Write update and delete operations on table data 4M


Ans. Update operations:
The UPDATE statement is used to change or modify the
existing records Correct
in a database table. operation
SQL query will be formed using the UPDATE statement and
WHERE statement 2M
clause, after that a query will be executed by passing it to the
PHPquery() each
function to update the tables records.
Example:
The percentage of roll no. C101 will be updated to 98.99 from
student ‟ ‟
table by using UPDATE statement.
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "UPDATE student SET percent=98.99
WHERE rollno='CO101'";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
?>
Delete operation:
Records can be deleted from a table using the SQL DELETE
statement.
SQL query is formed using the DELETE statement and
WHERE clause,
after that will be executed by passing this query to the PHP
query()
function to delete the tables records.
For example a student record with a roll no. „CO103 will be
deleted by ‟
using DELETE statement and WHERE clause.
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);

if ($conn->connect_error) die($conn->connect_error);
$query = "DELETE from student WHERE rollno='CO103'";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
?>
Q.12) Explain web server role in web development
Ans. The web server's role in PHP web development as
shown below:

1. HTTP Request Handling: When a user accesses a PHP-


based web
application, their browser sends an HTTP request to the web
server. The web
server receives this request and determines how to handle it
based on the
requested URL and the HTTP method used (e.g., GET, POST).
The server is
responsible for routing the request to the appropriate PHP
script or file for
processing.
2. PHP Script Execution: Once the web server receives an
HTTP request
that requires PHP processing, it passes the request to the PHP
interpreter or
engine. The PHP interpreter executes the PHP code contained
within the
requested file or script. It processes the logic, interacts with
databases,
performs computations, and generates dynamic HTML or
other types of
content.
3. Server-Side Processing: PHP is a server-side scripting
language, meaning
the PHP code is executed on the server before the resulting
HTML or other
output is sent back to the client's browser. The web server
runs the PHP script
in its environment and provides necessary resources like
database
connections, file access, and session management.
4. Integration with Other Technologies: In addition to
executing PHP code,
the web server may also be responsible for integrating with
other technologies
commonly used in web development. For example, the web
server can handle requests for static files like CSS, JavaScript,
and images,
delivering them directly to the client without involving PHP
processing. It
can also handle URL rewriting or redirection for search engine
optimization
(SEO) purposes or to create user-friendly URLs.
5. Content Delivery: Once the PHP script execution is
complete, the web
server sends the generated content (usually HTML) back to
the client's
browser as an HTTP response. The server sets the
appropriate headers, such
as Content-Type, Content-Length, and caching directives, to
ensure the
correct interpretation and rendering of the response by the
client.
6. Error Handling and Logging: The web server is responsible
for handling
errors and logging relevant information. If an error occurs
during PHP script
execution, the web server can be configured to display an
error message or
redirect to a custom error page. It also logs information about
requests, errors,
and server events, which can be helpful for debugging,
monitoring, and
performance analysis.

Q.13) Define session & cookie. Explain use of session start.


Ans:
Ans Cookie: Cookie is a small piece of information which is
stored at client browser. It is used
to recognize the user.

• Cookie is created at server side and saved to client browser.


Each time when client
sends request to the server, cookie is embedded with
request. Such way, cookie
can be received at the server side. In short, cookie can be
created, sent and
received at server end.
Session: Session data is stored on the server side and each
Session is assigned with a
unique Session ID (SID) for that session data. As session data
is stored on the server there
is no need to send any data along with the URL for each
request to server.
Session_start-
• PHP session_start() function is used to start the session.
• It starts a new or resumes existing session.
• It returns existing session if session is created already.
• If session is not available, it creates and returns new session
Session variables are set with the PHP global variable:
$_SESSION.
Example:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>

You might also like