0% found this document useful (0 votes)
6 views35 pages

Question Bank Final PHP

The document is a question bank for the Web Development Using PHP course at Parul Institute of Engineering and Technology for the 4th semester. It includes various questions covering PHP concepts such as variables, constants, data types, control structures, functions, and database integration. Each question is accompanied by explanations and examples to aid understanding of PHP programming.

Uploaded by

halen0778
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)
6 views35 pages

Question Bank Final PHP

The document is a question bank for the Web Development Using PHP course at Parul Institute of Engineering and Technology for the 4th semester. It includes various questions covering PHP concepts such as variables, constants, data types, control structures, functions, and database integration. Each question is accompanied by explanations and examples to aid understanding of PHP programming.

Uploaded by

halen0778
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/ 35

PARUL INSTITUTE OF

ENGINEERING AND
TECHNOLOGY (DIPLOMA
STUDIES)
COMPUTER ENGG.
DEPARTMENT

4th SEMESTER
Web Development Using PHP (03606265)
Question Bank
Academic Year : 2024-25
Web Development Using PHP-(03606265 )
QUESTION BANK

1. What is PHP? Explain its uses in web development.


2. What are the rules for naming variables in PHP?
3. What is a constant in PHP, and how is it different from a variable?
4. What is the purpose of the echo and print statements in PHP?
5. What are the data types in PHP? Provide an example of any two.
6. What are the types of operators in PHP? Explain Arithmetic operator with
example.
7. What is the basic syntax of an if statement in PHP? Provide an example.
8. Write a PHP program using if and else to check whether a number is even or
odd.
9. What is the syntax of a for loop in PHP? Write a for loop to print numbers
from 1 to 5.
10. What is the difference between a while loop and a do-while loop in PHP?
11. Define: 1) switch statement 2) continue statement 3)break statement
12. Explain the concept of a function in PHP. Why are functions important in
programming?
13. What is the difference between Call by Value and Call by Reference in PHP?
Explain with an example of each.
14. What is a recursive function? Write a recursive PHP function to calculate the
factorial of a number.
15. What is the purpose of the strlen() function in PHP? How would you use it to
find the length of a string?
16. Explain the strcmp() function in PHP. How would you compare two strings
for equality or ordering? Provide an example.
17. How do you reverse a string in PHP? What function do you use, and how
does it work?
18. What are the different types of arrays in PHP? Explain the difference between
indexed arrays, associative arrays with examples.
19. Explain the significance of the Array identifier and how it is used in PHP.
Provide examples demonstrating its usage.
20. What are Associative Arrays in PHP? Provide an example demonstrating the
use of Associative Arrays.
21. How can you define a starting index value for an array in PHP? Provide a
code example.
22. What is the difference between a cookie and a session in PHP?
23. Explain the setcookie() function with its parameters and how it works in PHP.
24. Explain what a session is and how it is different from a cookie.
25. Write a PHP script that deletes a session variable.
26. Explain the session_start() function and why it needs to be called at the
beginning of a PHP script that uses sessions.
27. Which functions are used to integrate php with MySQL.
28. Give sysntax :1)mysqli_connect() 2)mysqli_selectdb().
29. What is the difference between the $_GET and $_POST methods in PHP?
30. Write php script to create database in MySQL.
31. Explain mysqli_query() function with example.
32. Write php script to insert record in MySQL table.
CHAPTER:1 INTRODUCTION TO PHP

1. What is PHP? Explain its uses in web development.


Answer: -
 PHP is a Server side Scripting Language that is used for building
dynamic and interactive web application.
 PHP is Case sensitive.
 PHP Scripts sun on a webserver.
 PHP stands For Hypertext preprocessor.
 one of the key features of PHP is that you can embed PHP code within
HTML web pages- PHP Script can sun on various operating System
such as windows,linux, Unix,etc.
 The basic syntax for a PHP script starts with the PHP opening tag <?php
and ends with the closing tag ?>
 Syntax:
<?php
echo "Hello, World!";
?>

Uses of PHP in Web Development:

 Server-side scripting to handle backend tasks.


 Database interaction (e.g., MySQL) for dynamic content.
 Form processing, validation, and security.
 Session management (user authentication, cookies).
 Creating web applications and APIs.
2. What are the rules for naming variables in PHP?
Answer: -
 The rules for naming variables in PHP are as follows:

1) A variable name always starts with $(dollassr)sign.


2) A variable name must start with a letter (a-z, A-Z) or an underscore
(_).
3) The subsequent characters can be letters, numbers (0-9), or
underscores.
4) Variable names are case-sensitive, meaning $name and $Name are
different variables.
5) A variable cannot start with a number(digits).
6) No spaces or special characters (except underscores) are allowed in
variable names.

Example:

$name = "Sana"; // Valid


$_age = 25; // Valid
$1st_name = "Dev"; // Invalid (cannot start with a number)

3. What is a constant in PHP, and how is it different from a variable?


Answer: -
 A constant is a value that cannot be changed once it is defined. In
PHP, constants are defined using the define() function, and their
values remain fixed throughout the script's execution. Unlike
variables, constants do not require a dollar sign ($) before their name
and cannot be re-assigned once they are set.

 Differences between Variables and Constants:

 Variables: Can change values during script execution, and their


names begin with a $.
 Constants: Have a fixed value and are not prefixed with a $. They
are typically used for values that should remain constant (like
configuration values).
Example:
define("PI", 3.14159); // Constant
$radius = 5; // Variable

4. What is the purpose of the echo and print statements in PHP?


Answer: -
1) echo
 It accepts one or more strings as an argument and display one or more
strings on the browser.
 The echo statement does not return any value.
 It is faster as compared to print statement.
 Syntax: echo string
 Example: -
<?php
echo "Hello" ;
echo " I am Fine”;
?>
Output:
Hello I am Fine;
2) Print
 The print statement is basically used to display string or value of
variable.
 The print statement accepts only one string as an argument and displays
it on browser.
 The point statement always returns.It is slower as compared to echo
statement.
 Syntax: print string
 Example: -
<?php
print "Hello“.”how”.”are”.”you”,<br/>;
echo " I am Fine”;
?>

 Output:
Hellohowareyou
I am Fine;

5. What are the data types in PHP? Provide an example of any two.
Answer: -
Datatypes:

1. String
2. Integer
3. Float
4. Boolean
5. Array
6. Object
7. NULL
8. Resource

Example:

1) Integer

<?php
$num1 = 10;
$num2 = 5;
$sum = $num1 + $num2; // Sum of two integers
echo "The sum is: " . $sum; // Outputs: The sum is: 15
?>

2) String
<?php
// Define a string variable
$message = "Hello, World!";
// Print the string
echo $message; // Outputs: Hello, World!
?>

6. What are the types of operators in PHP? Explain Arithmetic operator


with example.
Answer: -
 Operators are used to perform operations on variables and values.
 PHP divides the operators in the following groups:

1) Arithmetic operators
2) Assignment operators
3) Comparison operators
4) Increment/Decrement operators
5) Logical operators
6) Ternary operator

1. Arithmetic Operators

 The PHP arithmetic operators are used with numeric values


to perform common arithmetical operations, such as
addition, subtraction, multiplication etc.
Example:
<?php
$a = 10;
$b = 4;

echo $a + $b; // Outputs: 14 (addition)


echo $a - $b; // Outputs: 6 (subtraction)
echo $a * $b; // Outputs: 40 (multiplication)
echo $a / $b; // Outputs: 2.5 (division)
?>
CHAPTER:2 Control Structure-Decisions and loop.

7. What is the basic syntax of an if statement in PHP? Provide an


example.
Answer: -
 PHP if statement allows conditional execution of code. It is executed
if condition is true.
 If statement is used to executes the block of code exist inside the if
statement only if the specified condition is true.
Syntax:
if(condition){
//code to be executed
}
Example:
<?php
$no=5;
if($no<10){
echo "$no is less than 10";
}
?>
Output:
12 is less than 100
8. Write a PHP program using if and else to check whether a number is
even or odd.
Answer: -
<?php
$no=10;
if($no%2==0)
{
echo "$no is Even Number";
}
else
{
echo "$ no is Odd Number";
}
?>

9. What is the syntax of a for loop in PHP? Write a for loop to print
numbers from 1 to 5.
Answer: -
 PHP for loop can be used to traverse set of code for the specified
number of times.
 It should be used if the number of iterations is known otherwise use
while loop. This means for loop is used when you already know how
many times you want to execute a block of code.
Syntax:
for (initialization; condition; increment/decrement){
//code to be executed
}
initialization - Initialize the loop counter value. The initial value of the for
loop is done only once. This parameter is optional.
condition - Evaluate each iteration value. The loop continuously executes
until the condition is false. If TRUE, the loop execution continues,
otherwise the execution of the loop ends.
Increment/decrement - It increments or decrements the value of the
variable.
To Print 1 to 5 numbers.

<?php
for($n=1;$n<=5;$n++){
echo "$n<br/>";
}
?>
Output:
1
2
3
4
5

10. What is the difference between a while loop and a do-while loop in
PHP?
Answer: -

WHILE LOOP DO WHILE


The while loop is also named as entry The do-while loop is also named
control loop. as exit control loop.
The body of the loop does not execute The body of the loop executes at least
if the condition is false. once, even if the condition is false.
Condition checks first, and then block Block of statements executes first and
of statements executes. then condition checks.
This loop does not use a semicolon to Do-while loop use semicolon to
terminate the loop. terminate the loop.
Syntax:
Syntax:
while(condition){ do{
//code to be executed //code to be executed
} }while(condition);

e.g:
e.g:
<?php
$n=1; <?php
while($n<=5){ $n=1;
echo "$n<br/>"; do{
$n++; echo "$n<br/>";
} $n++;
?> }while($n<=5);
?>

11. Define: 1) switch statement 2) continue statement 3) break statement


Answer: -
1) Switch statement

 PHP switch statement is used to execute one statement from


multiple conditions. It works like PHP if-else-if statement.
Syntax:
switch(expression){
case value1:
break;
case value2:
break;
......
default:
//code to be executed if all cases are not matched;
}
Example:
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
Output:
number is equal to 20

2) Continue statement

 The continue statement is used within looping and switch control


structure when you immediately jump to the next iteration.
Syntax:
jump-statement;
continue;

Example:
<?php
//outer loop
for ($i =1; $i<=3; $i++) {
//inner loop
for ($j=1; $j<=3; $j++) {
if (!($i == $j) ) {
continue; //skip when i and j does not have same values
}
echo $i.$j;
echo "</br>";
}
}
?>
Output:
11
22
33
3) break statement

 The break statement can also be used to jump out of a loop.


Syntax:
jump statement;
break;
Example:
<?php
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i==5){
break;
}
}
?>
Output:
1
2
3
4
5
CHAPTER:3 Functions and Strings

12. Explain the concept of a function in PHP. Why are functions


important in programming?
Answer: -
In PHP, a function is a reusable block of code that performs a specific task.
Functions are defined once and can be invoked (called) multiple times in a
program, which helps to reduce code repetition and improve
maintainability.
 Types of Functions in PHP:

1) User-defined functions: User-defined functions are custom


functions created by the programmer to perform specific tasks.
2) Built-in functions: Built-in functions are predefined functions
provided by PHP to perform common tasks.

 How Does a Function Work?


Define the Function: You create a function using the function keyword,
give it a name, and write the code inside curly braces {}.
Call the Function: You use the function's name to run the code inside it.
 Why Are Functions Important in Programming?

2. They save time and make the program easier to manage.


3. They help in writing clean and organized code.
4. They allow programmers to focus on solving the main problem
by reusing tested and working code
Example:
<?php
// Function Definition
function sayHello() {
echo "Hello, welcome to learning PHP functions!";
}
// Call the Function
sayHello();
?>
Output:
Hello, welcome to learning PHP functions!

13. What is the difference between Call by Value and Call by Reference
in PHP? Explain with an example of each.
Answer: -
1) Call by Value

 In Call by Value, a copy of the variable's value is passed to the


function.
 Changes made to the parameter inside the function do not affect the
original variable outside the function.

Example:

<?php
function add($num) {

$num += 10; // This change only affects the local copy


echo "Inside Function: $num\n"; // Outputs: 20
}

$original = 10;
add($original); // Call by Value
echo "Outside Function: $original\n"; // Outputs: 10
?>

2) Call by Reference

 In Call by Reference, the reference (memory address) of the


variable is passed to the function.
 Changes made to the parameter inside the function affect the
original variable outside the function.
Example:

<?php

function add(&$num) {

$num += 10; // This change affects the original variable

echo "Inside Function: $num\n"; // Outputs: 20

$original = 10;

add($original); // Call by Reference

echo "Outside Function: $original\n"; // Outputs: 20

?>

Call By Value Call By Reference

While calling a function, instead of


While calling a function, we pass
passing the values of variables, we pass
the values of variables to it. Such
the address of variables(location of
functions are known as “Call By
variables) to the function known as
Values”.
“Call By References.

In this method, the value of each In this method, the address of actual
variable in the calling function is variables in the calling function is
copied into corresponding dummy copied into the dummy variables of the
variables of the called function. called function.

With this method, the changes


With this method, using addresses we
made to the dummy variables in
would have access to the actual
the called function have no effect
variables and hence we would be able to
on the values of actual variables in
manipulate them.
the calling function.
Call By Value Call By Reference

In call-by-values, we cannot alter In call by reference, we can alter the


the values of actual variables values of variables through function
through function calls. calls.

Values of variables are passed by Pointer variables are necessary to define


the Simple technique. to store the address values of variables.

This method is preferred when we This method is preferred when we have


have to pass some small values to pass a large amount of data to the
that should not change. function.

Call by value is considered safer Call by reference is risky as it allows


as original data is preserved direct modification in original data

14. What is a recursive function? Write a recursive PHP function to


calculate the factorial of a number.
Answer: -
 A recursive function is a function that calls itself to solve smaller instances
of the same problem.
<?php
// Recursive function to calculate factorial
function factorial($n) {
// Base case: factorial of 0 or 1 is 1
if ($n <= 1) {
return 1;
}
// Recursive case: n * factorial(n-1)
return $n * factorial($n - 1);
}
// Test the function
$number = 5;
echo "The factorial of $number is: " . factorial($number); // Outputs:
The factorial of 5 is: 120
?>

 Advantages of Recursive Functions

1) Simplifies problems that have a repetitive structure (e.g., factorial,


Fibonacci series, tree traversals).
2) Reduces the need for loops in some scenarios.

 Disadvantages of Recursive Functions

1) Can lead to stack overflow if the recursion depth is too high.


2) May be less efficient due to repeated function calls.

15. What is the purpose of the strlen() function in PHP? How would you
use it to find the length of a string?
Answer: -
 The strlen() function in PHP is used to calculate the length of a string, i.e.,
it returns the number of characters present in the string. This includes all
characters, spaces, and special characters.
 Syntax:
strlen(string);
 Parameter: The function takes a single parameter, which is the string
whose length you want to find.
 Return Value: It returns an integer representing the number of characters
in the string.
Example:
<?php
$string = "Hello, PHP!";
$length = strlen($string);
echo "The length of the string is: $length";
?>
Outputs:
The length of the string is: 12

16. Explain the strcmp() function in PHP. How would you compare two
strings for equality or ordering? Provide an example.
Answer: -
 The strcmp() function in PHP is used to compare two strings. It performs
a case-sensitive comparison, meaning that uppercase and lowercase letters
are considered different. The function returns an integer value based on the
comparison:
 Returns 0: If the two strings are identical.
 Returns a value less than 0: If the first string is less than the second string.
 Returns a value greater than 0: If the first string is greater than the second
string.
Syntax:
strcmp(string1, string2);
To compare two strings:
 Use strcmp() to check if two strings are equal or if one is greater than
the other.
 The result can be used in conditional statements or for sorting.
Example:
<?php
$string1 = "Hello";
$string2 = "hello";

if ($string1 == $string2) {
echo "The strings are equal."; // This will NOT print.
} else {
echo "The strings are not equal."; // This will print.
}
?>

17. How do you reverse a string in PHP? What function do you use, and
how does it work?
Answer: -
 In PHP, you can reverse a string using the built-in function strrev(). This
function takes a string as input and returns the string with its characters in
reverse order.
Syntax:
strrev(string);
Example:
<?php
$string = "Hello, PHP!";
$reversedString = strrev($string);
echo $reversedString;
?>
Outputs:
!PHP ,olleH
CHAPTER:4 PHP Arrays and Handling Html Form with Php

18. What are the different types of arrays in PHP? Explain the difference
between indexed arrays, associative arrays with examples.

Answer: -
 In PHP, an array is a data structure that allows you to store multiple values
in a single variable.

The different types of arrays in PHP include:


1. Indexed Arrays
2. Associative Arrays
3. Multidimensional Arrays

Indexed Arrays Associative Arrays


These arrays use named keys to
These arrays use numeric indices to access elements. Each element is
access elements, starting from 0. associated with a specific key.

e.g:
e.g:
$assocArray = array("name" =>
$indexedArray=array("Apple", "John", "age" => 25, "city" => "New
"Banana", "Orange"); York");

19. Explain the significance of the Array identifier and how it is used in
PHP. Provide examples demonstrating its usage.

Answer: -
 In PHP, the $ symbol is used to indicate variables. The array identifier, $,
followed by the array variable name is used to access or manipulate array
elements.

 For example: $fruits = array("Apple", "Banana", "Orange");


 The array identifier is crucial for working with arrays as it allows you to
interact with individual elements based on their position or key.

20. What are Associative Arrays in PHP? Provide an example


demonstrating the use of Associative Arrays.

Answer: -
Associative Arrays in PHP are arrays where each element is associated
with a specific key rather than a numeric index.

Here's an example:

// Associative array with key-value pairs


$userInfo = array( "name" => "John Doe", "age" => 30, "city" => "New
York" );
// Accessing elements using keys
$userName = $userInfo["name"]; // $userName is now "John Doe"
$userAge = $userInfo["age"]; // $userAge is now 30

In this example, the keys "name," "age," and "city" are associated with
corresponding values, forming an associative array. This allows for more
descriptive and meaningful indexing compared to traditional indexed
arrays.

21. How can you define a starting index value for an array in PHP?
Provide a code example.

Answer: -
In PHP, define a starting index value for an array by explicitly assigning
values to specific indices.

Here's an example:

// Defining an array with a starting index of 1


$arrayWithIndex = array(1 => "Apple", 2 => "Banana", 3 => "Orange");
// Accessing elements with the defined index
$secondElement = $arrayWithIndex[2]; // $secondElement is now
"Banana"
In this example, the array starts with an index of 1, and subsequent indices
are assigned accordingly.
CHAPTER:5 Session and Cookie

22. What is the difference between a cookie and a session in PHP?


Answer: -

Cookies Session

Cookies are client-side files on


Sessions are server-side files that contain
a local computer that hold user
user data.
information.

Cookies end on the lifetime set When the user quits the browser or logs out
by the user. of the programmed, the session is over.

It can only store a certain


It can hold an indefinite quantity of data.
amount of info.

We can keep as much data as we like within


The browser’s cookies have a a session, however there is a maximum
maximum capacity of 4 KB. memory restriction of 128 MB that a script
may consume at one time.

Because cookies are kept on


the local computer, we don’t To begin the session, we must use the
need to run a function to start session start() method.
them.

Session are more secured compare than


Cookies are not secured.
cookies.

Cookies stored data in text file. Session save data in encrypted form.

Cookies stored on a limited


Session stored a unlimited data.
data.

In PHP, to get the data from


In PHP , to get the data from Session,
Cookies , $_COOKIES the
$_SESSION the global variable is used
global variable is used
Cookies Session

In PHP, to destroy or remove the data


We can set an expiration date
stored within a session, we can use the
to delete the cookie’s data. It
session_destroy() function, and to unset a
will automatically delete the
specific variable, we can use the unset()
data at that specific time.
function.

23. Explain the setcookie() function with its parameters and how it works
in PHP.
Answer: -
 The setcookie() function in PHP is used to send a cookie from the server
to the client's browser. Cookies are small pieces of data that are stored on
the user's computer and can be used to maintain user-specific information
across multiple pages or sessions.
 Syntax of setcookie():
setcookie(name, value, expire, path, domain, secure, httponly);
Parameters of setcookie()

1. name (Required):
o The name of the cookie. This is the identifier used to retrieve the
cookie's value on the client side.
o Example: "username"
2. value (Optional):
o The value associated with the cookie. This is the data you want to
store in the cookie.
o Example: "JohnDoe"
o If this parameter is not set, the cookie will be deleted.
3. expire (Optional):
o The expiration time of the cookie, specified as a timestamp (a Unix
timestamp). It defines when the cookie will expire.
o A value of 0 or a negative number will make the cookie a session
cookie, which expires when the browser is closed.
o Example: time() + 3600 (cookie expires in 1 hour from the current
time).
o Example: time() + 3600 * 24 * 30 (cookie expires in 30 days).
4. path (Optional):
o The path on the server where the cookie will be available. The
default value is /, meaning the cookie will be available throughout
the entire domain.
o Example: / (available to the whole domain), /folder/ (only available
within /folder/).
5. domain (Optional):
o The domain that the cookie is available to. This defines which
domains can access the cookie. The default is the domain of the
calling script.
o Example: "example.com" (the cookie will be available to this
domain and subdomains).
6. secure (Optional):
o A boolean value that indicates whether the cookie should only be
sent over a secure HTTPS connection.
o Set it to true if the cookie should only be sent over HTTPS.
o Example: true (only sent over HTTPS) or false (sent over HTTP as
well).
7. httponly (Optional):
o A boolean value that specifies whether the cookie should be
accessible via JavaScript. If set to true, the cookie is not accessible
via JavaScript (helps mitigate the risk of cross-site scripting attacks).
o Example: true (not accessible via JavaScript) or false (accessible via
JavaScript).

24. Explain what a session is and how it is different from a cookie.

 A session in PHP is a way to store user-specific information on the


server during a user's interaction with a website. Unlike cookies, which
store data on the client's computer, session data is stored on the server.
A session is typically used to retain user information across multiple
pages (for example, user login information, shopping cart contents, etc.)
while the user is browsing the website.
 Starting a Session:

<?php

// Start the session

session_start();

// Set session variables


$_SESSION["username"] = "JohnDoe";

$_SESSION["user_id"] = 12345;

// Access session variables

echo "Hello, " . $_SESSION["username"];

?>

 Sessions are more secure because they store data on the server, making
them suitable for sensitive information that should not be exposed to
the client.
 Cookies are stored on the client side, making them more appropriate for
non-sensitive, persistent data that needs to be stored on the user's
device.

25. Write a PHP script that deletes a session variable.


Answer: -
<?php
// Start the session
session_start();

// Set a session variable


$_SESSION["username"] = "JohnDoe";

// Display the session variable before deletion


echo "Before deletion: " . $_SESSION["username"] . "<br>";

// Delete the session variable


unset($_SESSION["username"]);

// Check if the session variable is deleted


if (!isset($_SESSION["username"])) {
echo "Session variable 'username' has been deleted.<br>";
} else {
echo "Session variable 'username' still exists.<br>";
}
?>

26. Explain the session_start() function and why it needs to be called at


the beginning of a PHP script that uses sessions.
Answer: -
The session_start() function in PHP is used to start a new session or
resume the existing session for the current user. This function enables you
to access and manage session variables, which are stored on the server.
Once a session is started, PHP automatically assigns a unique session ID
to the user, which is used to track the session between the client and the
server.
Syntax:
session_start();
Why Does session_start() Need to Be Called at the Beginning of a PHP
Script?

The session_start() function must be called before any output is sent to


the browser, including any HTML tags, spaces, or text. This is because
session_start() sends HTTP headers to the browser, and HTTP headers
must be sent before any other output.

Example:

<?php

// Start the session at the very beginning of the script

session_start();

// Set session variables

$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "[email protected]";

// Access session variables

echo "Welcome, " . $_SESSION["username"];

?>
CHAPTER:6 PHP Database
27. Which functions are used to integrate php with MySQL.
Answer: -
It is possible to execute various commands of MySQL from PHP
application. PHP provides various built in functions that allow you to use
MySQL commands from PHP page. Thus you can integrate PHP with.
MySQL.
Following are the various functions of PHP that allows you the facility of
integrating PHP with. MySQL.
1 mysqli_connect()
2 mysqli_select db()
3 mysqli_query()
4 mysqli_fetch_row()
5 mysqli_fetch_array()
6 mysqli_error()
7 mysqli_num_rows()
8 mysqli_close()

28. Give syntax :1)mysqli_connect() 2)mysqli_selectdb().


Answer: -
1. mysqli_connect()=$variablename=mysql_connect(servername,us
ername,password)
2. mysqli_selectdb()=mysql_selectdb(“database name”);
29. What is the difference between the $_GET and $_POST methods in
PHP?
Answer: -
GET POST
Only a limited amount of data can A large amount of data can be sent
be sent because data is sent in the because data is sent in the body.
header.
GET request is not secured because POST request is secured because
the query string is appended in the data is not exposed in the URL bar.
URL bar.
GET request can be bookmarked. POST request cannot be
bookmarked.
A GET request is often cacheable. A POST request is hardly
cacheable.
GET request is more efficient and POST request is less efficient and
used more than POST. used less than GET.

30. write php script to create database in MySQL.


Answer: -
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}.
// Creating a database named newDB
$sql = "CREATE DATABASE newDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully with the name newDB";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
// closing connection
mysqli_close($conn);
?>

31. Explain mysqli_query() function with example.


Answer: -
mysqli_query() :
This function allows you to specify and execute the MySQL command o
MySQL Server.
Syntax : Mysqli_query ("Query", ConnectionName);
Query: Indicates the MySQL command to be executed. ConnectionName
: Indicates the name of the variable that is used at the time of establish
connection with MySQL server using mysqli_connect ( function.
Example:
<?php
$con = mysqli_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$sql = "SELECT * FROM Person";
mysqli_query($sql,$con);
mysqli_close($con);
?>
32. write php script to insert record in MySQL table.
Answer: -
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
$sql = "create table emp5(id INT AUTO_INCREMENT,name
VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL,primary key (id))";
if(mysqli_query($conn, $sql))
{
echo "Table emp5 created successfully";
}else{
echo "Could not create table: ". mysqli_error($conn);
}
mysqli_close($conn);
?>

You might also like