IMPORTANT
QUESTIONS OF PHP
UNIT
– I :- INTRODUCTION TO PHP.
Short Questions and Answers
1. What does PHP stand for?
Answer: PHP stands for Hypertext Preprocessor.
2. Who created PHP and in what
year?
Answer: PHP was created by Rasmus Lerdorf in 1994.
3. What is the role of Apache in
the AMP stack?
Answer: Apache acts as the web server, handling HTTP requests and
serving PHP-generated web pages.
4. Is MySQL an open-source
database?
Answer: Yes, MySQL is an open-source relational database management
system.
5. What is the AMP module?
Answer: AMP refers to Apache, MySQL, and PHP, a popular open-source
stack for building dynamic web applications.
6. What file is used to configure
PHP settings?
Answer: The `php.ini` file is used to configure PHP settings.
7. Can PHP run on IIS?
Answer: Yes, PHP can be configured to run on Microsoft’s Internet
Information Services (IIS).
8. What is the default port for
Apache web server?
Answer: The default port for Apache is 80 for HTTP and 443 for HTTPS.
9. What is the primary function of
MySQL in the AMP stack?
Answer: MySQL manages and stores data for web applications, interacting
with PHP for dynamic content.
10. Is PHP an open-source language?
Answer: Yes, PHP is open-source and freely available under the PHP
License.
What is Open Source software?
Ans: Open Source software is
software with source code freely available for modification and redistribution
by anyone.
---
6. What is the AMP stack?
Ans: AMP stands for Apache, MySQL,
PHP — a common set of software used to develop and run dynamic websites on a
server.
---
7. Mention two ways to configure PHP on a web
server.
Ans: PHP can be configured using:
- Apache Web Server
- IIS (Internet Information
Services)
----------------------------------------------------------------------------------------------
Long Questions and Answers
1. Explain the history and
evolution of PHP.
Ans:
PHP was created by Rasmus Lerdorf
in 1994 initially as a set of Common Gateway Interface (CGI) binaries written
in C. It was called "Personal Home Page Tools."
Over time, it evolved into a
full-fledged scripting language and was renamed PHP: Hypertext Preprocessor.
- PHP 3 (1998): Official launch
with strong support for databases.
- PHP 4 (2000): Improved
performance with Zend Engine 1.0.
- PHP 5 (2004): Introduced OOP
concepts and better XML support.
- PHP 7 (2015): Major performance
boost and reduced memory usage.
- PHP 8 (2020): Introduced JIT
compilation and other enhancements.
2. Describe the relationship
between Apache, MySQL, and PHP in the AMP stack and how they work together to
deliver dynamic web content.
Answer:
The AMP stack (Apache, MySQL, PHP) is a cohesive set of open-source
technologies used to build and serve dynamic web applications. Each component
has a distinct role, and they interact seamlessly to deliver content:
- Apache: The web server handles incoming HTTP/HTTPS requests from
browsers. It serves static content (e.g., HTML, CSS, images) directly and
delegates dynamic requests (e.g., .php files) to the PHP processor via modules
like `mod_php`. Apache routes responses back to the client.
- MySQL: This relational database management system stores and manages
application data, such as user information, posts, or product details. PHP
queries MySQL using extensions like `mysqli` or PDO to retrieve or manipulate
data.
- PHP: The server-side scripting language processes requests, generates
dynamic content, and interacts with MySQL to fetch or update data. PHP scripts
are executed by the server, producing HTML or other output sent to the client
via Apache.
Together, they enable dynamic
websites: a user requests a page, Apache receives it, PHP processes the logic
and queries MySQL for data, and Apache delivers the resulting HTML to the
browser. The open-source nature of AMP ensures cost-effectiveness, community
support, and flexibility, making it a popular choice for platforms like
WordPress, Joomla, and custom applications.
4. Explain how to configure PHP on
Microsoft IIS (Internet Information Services) and the key differences from
configuring it on Apache.
Answer:
Configuring PHP on Microsoft IIS allows PHP applications to run on
Windows servers. Below is a step-by-step guide, followed by differences from
Apache:
Steps to Configure PHP on IIS:
1. Install IIS: Ensure IIS is enabled on Windows Server or Windows
Pro/Enterprise. Go to “Turn Windows features on or off,” enable “Internet
Information Services,” and include CGI support under “Application Development
Features.” Alternatively, install via PowerShell:
Install-WindowsFeature -Name Web-Server,
Web-CGI
2. Download PHP: Download the non-thread-safe (NTS) version of PHP for
Windows from `https://windows.php.net/download/`. Extract it to a directory,
e.g., `C:\PHP`.
3. Configure PHP: Rename `php.ini-development` to `php.ini` in `C:\PHP`.
Edit `php.ini` to enable extensions (e.g., `extension=mysqli`) and set
parameters like `extension_dir = "C:\PHP\ext"`.
4. Install PHP Manager for IIS (optional, simplifies configuration):
Download PHP Manager from `https://github.com/phpmanager/phpmanager` and
install it. Use it to register PHP with IIS and configure settings.
5. Configure IIS to Handle PHP: Open IIS Manager, select the server, and
open “Handler Mappings.” Add a “FastCGI Module Mapping”:
- Request path: `*.php`
- Module: FastCGIModule
- Executable: `C:\PHP\php-cgi.exe`
- Name: PHP via FastCGI
Save and apply.
6. Set Default Document: In IIS Manager, ensure `index.php` is added to
the “Default Document” list for your site.
7. Test PHP: Create a file, e.g., `C:\inetpub\wwwroot\info.php`,
with:
<?php phpinfo(); ?>
Access `http://localhost/info.php` in a
browser to verify PHP is working.
8. Secure the Setup: Remove `info.php`, restrict `C:\PHP` folder
permissions, and configure IIS security settings (e.g., authentication,
SSL).
Key Differences from Apache:
- Architecture: Apache uses modules like `mod_php` for PHP integration,
processing PHP within the server process. IIS uses FastCGI, running PHP as a
separate process, which can improve stability but requires additional
configuration.
- Configuration: Apache relies on text-based configuration files (e.g.,
`httpd.conf`), while IIS uses a GUI (IIS Manager) or XML-based files (e.g.,
`web.config`).
- Platform: Apache is cross-platform, while IIS is Windows-specific,
limiting its use to Microsoft environments.
- Performance: Apache with `mod_php` can be faster for PHP execution,
but IIS with FastCGI offers better isolation and scalability for Windows-based
applications.
- Ease of Use: Apache’s AMP stack is more standardized for PHP, with
simpler setup on Linux. IIS requires manual FastCGI setup or tools like PHP
Manager, which can be less intuitive for PHP developers.
Both servers support PHP effectively, but Apache is more common in
open-source environments, while IIS is preferred in Windows-centric enterprise
settings.
5. Discuss the open-source
relationship between Apache, MySQL, and PHP, and why this makes the AMP stack
popular for web development.
Answer:
The AMP stack (Apache, MySQL, PHP) is built on open-source software,
meaning their source code is freely available, modifiable, and distributable
under licenses like the Apache License (Apache), GNU GPL (MySQL), and PHP
License (PHP). This open-source relationship drives the stack’s popularity for
several reasons:
- Cost-Effectiveness: All components are free, reducing development and
hosting costs for individuals, startups, and enterprises. This accessibility
democratizes web development.
- Community Support: A global community of developers contributes to
updates, bug fixes, and documentation. Forums, tutorials, and resources (e.g.,
Stack Overflow, Apache Friends) provide extensive support, making it easier to
troubleshoot and learn.
- Flexibility and Customization: Open-source nature allows developers to
modify Apache, MySQL, or PHP to suit specific needs, such as custom modules or
performance optimizations. This flexibility supports diverse applications, from
blogs to e-commerce platforms.
- Interoperability: Apache, MySQL, and PHP are designed to work
seamlessly together. Apache’s `mod_php` processes PHP scripts, which use
extensions like `mysqli` to query MySQL, creating a cohesive ecosystem for
dynamic web applications.
- Cross-Platform Support: The stack runs on Linux, Windows, and macOS,
with tools like XAMPP and WAMP simplifying setup. This portability suits varied
hosting environments.
- Widespread Adoption: The open-source model has led to widespread use,
powering platforms like WordPress, Drupal, and Joomla. This popularity ensures
compatibility with hosting providers and a large pool of developers familiar
with the stack.
- Continuous Improvement: Community-driven development ensures regular
updates, security patches, and new features. For example, PHP 8 introduced JIT,
MySQL 8 improved performance, and Apache remains robust for modern web
needs.
2. Describe the role of Apache Web Server in
the PHP ecosystem.
Ans:
Apache is an open-source HTTP
server that helps in delivering web content to clients. It works with PHP
by:
- Processing client requests
- Executing PHP scripts using the
PHP interpreter
- Returning the result (HTML) to
the browser
Apache supports mod_php to directly
embed the PHP interpreter in the web server for better performance. It's widely
used due to flexibility, modules, and compatibility with PHP.
---
3. Discuss the relationship between Apache,
MySQL, and PHP (AMP stack).
Ans:
The AMP stack stands for Apache,
MySQL, and PHP, which together form a popular framework for developing dynamic
websites.
- Apache handles HTTP requests and
serves web pages.
- MySQL stores data in a structured
format (tables) and handles queries.
- PHP is used to create dynamic
content and interact with the database.
PHP scripts use MySQL functions (or
PDO) to retrieve and store data, and Apache sends the output back to the user's
browser. Together, they offer a complete web development environment.
---
4. Compare and explain PHP configuration in
IIS and Apache Web Server.
Ans:
| Feature |
PHP in Apache | PHP in IIS |
|---------------- |---------------------------------- |-------------------------------------|
| Platform |
Cross-platform (Linux/Windows) |
Mainly Windows |
| Integration |
Via `mod_php` or FastCGI | Via FastCGI |
| Configuration |
`httpd.conf`, `php.ini` | IIS Manager, `php.ini` |
| Performance |
Efficient on Linux | Can perform well with
FastCGI |
| Popularity |
More common with Apache | Used when integrating with .NET |
Steps for Configuration in Apache:
1. Install Apache
2. Install PHP
3. Edit `httpd.conf` to load PHP
module
4. Set handler for `.php`
files
5. Restart Apache
Steps for Configuration in IIS:
1. Install IIS through Windows
features
2. Install PHP (using Web Platform
Installer or manually)
3. Configure FastCGI handler in
IIS
4. Set `.php` MIME type
5. Restart IIS
Both setups require editing the
`php.ini` file for additional configuration, like enabling extensions.
===========================================================================
UNIT-
II:- BASICS OF PHP:
1. What is the basic syntax of PHP?
Answer:
PHP scripts start with <?php and end with ?>. PHP statements end with a
semicolon. Example:
<?php
echo "Hello World!";
?>
2. How do you create a PHP page?
Answer:
To create a PHP page, save a file with .php extension and include PHP code
within <?php ?> tags. Example:
<?php
echo "This is a PHP
page.";
?>
3. Mention the rules of PHP syntax.
Answer:
- PHP
code must be enclosed in <?php ?>.
- Statements
end with a semicolon.
- Variables
start with $.
- PHP
is case-sensitive for variables.
4. How can HTML be integrated with
PHP?
Answer:
HTML can be written directly within a PHP file. Example:
<?php
echo
"<h1>Hello</h1>";
?>
5. What is a constant in PHP?
Answer:
A constant is a name for a value that doesn't change during script execution.
Defined using define().
Example: define("SITE_NAME", "MySite");
6. How do you declare variables in
PHP?
Answer:
Variables in PHP start with $ sign.
Example: $name = "John";
7. What are static and global
variables in PHP?
Answer:
- Static
variable:
Retains value between function calls.
- function
test() {
- static $x = 0;
- $x++;
- echo $x;
- }
- Global
variable:
Declared outside function, accessed inside using global keyword.
8. List different PHP conditional
statements.
Answer:
- if
- if...else
- if...elseif...else
- switch
9. What are the different types of
loops in PHP?
Answer:
- for
loop
- while
loop
- do...while
loop
- foreach
loop
10. What is the use of foreach
loop?
Answer:
Used to iterate over arrays.
Example:
$colors = ["red",
"green"];
foreach ($colors as $color) {
echo $color;
}
11. What are PHP operators?
Answer:
Operators perform operations on variables/values:
- Arithmetic
(+, -)
- Assignment
(=, +=)
- Comparison
(==, !=)
- Logical
(&&, ||)
What is PHP?
Answer: PHP (Hypertext Preprocessor) is a server-side scripting language
used for web development to create dynamic web pages.
2. What is the file extension for
PHP files?
Answer: `.php`
3. How do you write a basic PHP
script?
Answer: Enclose PHP code within `<?php` and `?>` tags. Example:
`<?php echo "Hello, World!"; ?>`
4. What is the purpose of the
`echo` statement in PHP?
Answer: The `echo` statement outputs data (e.g., text, variables) to the
browser.
5. What is a constant in PHP?
Answer: A constant is a value that cannot be changed during script
execution, defined using `define()` or the `const` keyword.
6. How do you declare a variable in
PHP?
Answer: Variables are declared with a `$` sign followed by the variable
name, e.g., `$name = "John";`
7. What is the difference between
`static` and `global` variables?
Answer: A `static` variable retains its value between function calls but
is local to the function. A `global` variable is accessible throughout the
script but must be explicitly declared using the `global` keyword inside
functions.
8. What are the main types of PHP
operators?
Answer: Arithmetic, Assignment, Comparison, Logical,
Increment/Decrement, String, and Array operators.
9. What is an array in PHP?
Answer: An array is a data structure that stores multiple values in a
single variable, accessed via indices or keys.
10. What is the `foreach` loop used
for?
Answer: The `foreach` loop iterates over arrays, accessing each
element’s key and value.
1. Explain different types of
variables in PHP with examples.
Answer:
PHP variables include:
- Local: Declared inside a function.
- Global: Declared outside and accessed
using global.
- Static: Retains value across calls
using static.
Example:
$globalVar = 10;
function demo() {
global $globalVar;
static $count = 0;
$count++;
echo $count . ", " . $globalVar;
}
2. Discuss conditional structures
in PHP with syntax and examples.
Answer:
- if:
if ($a > $b) echo "A is
greater";
- if...else:
if ($a == $b) echo
"Equal";
else echo "Not equal";
- switch:
switch($day){
case "Mon": echo "Monday"; break;
default: echo "Other day";
}
3. Describe arrays and different
types of arrays in PHP.
Answer:
- Indexed
array:
- $arr
= [1, 2, 3];
- Associative
array:
- $person
= ["name"=>"John", "age"=>25];
- Multidimensional
array:
- $matrix
= [[1,2], [3,4]];
4. Explain user-defined functions
in PHP with arguments and return values.
Answer:
Function syntax:
function greet($name) {
return "Hello " . $name;
}
echo greet("John");
- Default
argument:
function
greet($name="Guest") {
echo "Hello $name";
}
- Variable-length
argument:
Using ... operator:
function sum(...$nums) {
return array_sum($nums);
}
echo sum(1, 2, 3);
5. Describe different types of PHP
loops with examples.
Answer:
- for:
for($i=0; $i<5; $i++) echo $i;
- while:
$i=0;
while($i<5) { echo $i; $i++; }
- do...while:
$i=0;
do { echo $i; $i++; }
while($i<5);
- foreach:
$arr = [1,2,3];
foreach ($arr as $val) echo $val;
Long Questions
1. Explain the structure and syntax
of PHP with an example.
Answer: PHP scripts are embedded within `<?php ?>` tags in an HTML
file or saved as `.php` files. The syntax is case-sensitive for variables and
functions but not for keywords. Statements end with a semicolon (`;`).
Example:
php
<?php
$name = "Alice";
echo "Hello, $name!";
?>
This code declares a variable `$name` and outputs "Hello,
Alice!" to the browser.
2. How do you integrate HTML with
PHP? Provide an example.
Answer: PHP can be embedded within HTML to generate dynamic content. PHP
code is placed inside `<?php ?>` tags, and its output is rendered as part
of the HTML.
Example:
<!DOCTYPE html>
<html>
<body>
<h1>Welcome, <?php echo
"User!"; ?></h1>
<p>Current time: <?php echo
date("H:i:s"); ?></p>
</body>
</html>
This outputs a heading with "User!" and the current time
dynamically.
3. Discuss the rules of PHP syntax.
Answer:
- PHP code is enclosed in `<?php ?>` tags.
- Statements end with a semicolon (`;`).
- Variables start with `$`, followed by a letter or underscore.
- PHP is case-sensitive for variables, functions, and constants (unless
defined otherwise).
- Comments are written using `//` (single-line) or `/* */`
(multi-line).
- Whitespace is ignored except within strings.
Example:
<?php
// Single-line comment
$x = 5; /* Multi-line comment */
echo $x;
?>
4. Explain the difference between
constants and variables in PHP with examples.
Answer:
- Constants: Immutable values defined using `define("NAME",
value)` or `const NAME = value`. They are global and cannot be redefined.
- Variables: Mutable values declared with `$` and can change during
execution.
Example:
<?php
define("SITE_NAME", "MyWebsite"); // Constant
$user = "John"; // Variable
echo SITE_NAME; // Outputs: MyWebsite
$user = "Jane"; // Variable reassigned
echo $user; // Outputs: Jane
?>
---
CONDITIONAL STRUCTURE & LOOPING
Short Questions
1. What is a conditional statement
in PHP?
Answer: A conditional statement executes code based on a condition,
e.g., `if`, `else`, `elseif`, `switch`.
2. Name three types of loops in
PHP.
Answer: `for`, `while`, `foreach`.
3. What is the purpose of the
`break` statement?
Answer: The `break` statement exits a loop or switch statement
prematurely.
4. What does the `continue`
statement do in a loop?
Answer: The `continue` statement skips the current loop iteration and
proceeds to the next.
5. What is a `switch` statement?
Answer: A `switch` statement evaluates an expression and executes code
based on matching cases.
# Long Questions
1. Explain the `if-elseif-else` structure in PHP with an example.
Answer: The `if-elseif-else` structure evaluates conditions sequentially
and executes the corresponding block of code. If no condition is true, the
`else` block (if present) is executed.
Example:
<?php
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} else {
echo "Grade: C";
}
?>
Output: `Grade: B`
2. Discuss the `while` and
`do-while` loops in PHP with examples.
Answer:
- while loop: Executes as long as the condition is true.
- do-while loop: Executes at least once, then continues if the condition
is true.
Example:
<?php
// while loop
$i = 1;
while ($i <= 3) {
echo "$i ";
$i++;
}
// Output: 1 2 3
// do-while loop
$j = 1;
do {
echo "$j ";
$j++;
} while ($j <= 3);
// Output: 1 2 3
?>
3. Explain the `switch` statement
in PHP with an example.
Answer: The `switch` statement evaluates an expression and matches it
against multiple `case` values, executing the corresponding block. A `break`
statement prevents fall-through, and `default` handles unmatched cases.
Example:
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "End of the week!";
break;
default:
echo "Midweek day.";
}
?>
Output: `Start of the week!`
---
PHP OPERATORS
# Short Questions
1. What is an arithmetic operator
in PHP?
Answer: Arithmetic operators perform mathematical operations, e.g., `+`,
`-`, `*`, `/`, `%`.
2. What does the comparison
operator `===` do?
Answer: The `===` operator checks for equality in value and type.
3. What is the purpose of the
logical operator `&&`?
Answer: The `&&` operator returns true if both operands are
true.
4. What does the assignment
operator `=` do?
Answer: The `=` operator assigns a value to a variable.
5. What is the string concatenation
operator in PHP?
Answer: The `.` operator concatenates two strings.
# Long Questions
1. Explain the difference between
`==` and `===` operators in PHP with examples.
Answer:
- `==` checks for equality in value, ignoring type.
- `===` checks for equality in both value and type.
Example:
<?php
$a = 5;
$b = "5";
var_dump($a == $b); // Output:
bool(true)
var_dump($a === $b); // Output: bool(false)
?>
2. Discuss logical operators in PHP
with examples.
Answer: Logical operators (`&&`, `||`, `!`) evaluate
conditions:
- `&&` (AND): True if both conditions are true.
- `||` (OR): True if at least one condition is true.
- `!` (NOT): Inverts the truth value.
Example:
<?php
$x = 10;
$y = 20;
if ($x > 5 && $y < 30) {
echo "Both conditions true!";
}
if ($x > 15 || $y > 15) {
echo "At least one condition
true!";
}
if (!($x == 10)) {
echo "Condition is false!";
} else {
echo "Condition is true!";
}
?>
---
ARRAYS & FOREACH LOOP
# Short Questions
1. What are the types of arrays in
PHP?
Answer: Indexed, Associative, and Multidimensional arrays.
2. How do you create an indexed
array in PHP?
Answer: `$array = [1, 2, 3];` or `$array = array(1, 2, 3);`
3. What is an associative array?
Answer: An array with named keys, e.g., `$ages = ["John" =>
25, "Jane" => 30];`
4. What does the `foreach` loop do
with arrays?
Answer: It iterates over each element of an array, accessing keys and
values.
5. How do you access an array
element?
Answer: Use the index or key, e.g., `$array[0]` or
`$array["key"]`.
# Long Questions
1. Explain the difference between
indexed and associative arrays in PHP with examples.
Answer:
- Indexed arrays: Use numeric indices (starting from 0).
- Associative arrays: Use named keys.
Example:
<?php
// Indexed array
$colors = ["Red", "Green", "Blue"];
echo $colors[1]; // Output: Green
// Associative array
$ages = ["John" => 25, "Jane" => 30];
echo $ages["Jane"]; // Output: 30
?>
2. Discuss the `foreach` loop in
PHP with an example for both indexed and associative arrays.
Answer: The `foreach` loop iterates over arrays, optionally accessing
both keys and values.
Example:
<?php
// Indexed array
$fruits = ["Apple", "Banana", "Orange"];
foreach ($fruits as $fruit) {
echo "$fruit ";
}
// Output: Apple Banana Orange
// Associative array
$scores = ["Math" => 90, "Science" => 85];
foreach ($scores as $subject => $score) {
echo "$subject: $score ";
}
// Output: Math: 90 Science: 85
?>
3. What is a multidimensional
array? Provide an example.
Answer: A multidimensional array is an array containing one or more
arrays, often used to represent tables or matrices.
Example:
<?php
$students = [
["John", 20, "A"],
["Jane", 22, "B"]
];
echo $students[1][0]; // Output: Jane
?>
---
USER-DEFINED FUNCTIONS
# Short Questions
1. What is a user-defined function
in PHP?
Answer: A function created by the programmer to perform a specific task,
defined using the `function` keyword.
2. How do you define a function in
PHP?
Answer: `function functionName() { code; }`
3. What is a function argument in
PHP?
Answer: A value passed to a function to be used in its execution.
4. What does the `return` statement
do in a function?
Answer: The `return` statement exits the function and sends a value back
to the caller.
5. What is a default argument in
PHP?
Answer: A function parameter with a predefined value used if no argument
is passed.
# Long Questions
1. Explain how to create and use a
user-defined function in PHP with an example.
Answer: A user-defined function is created using the `function` keyword,
followed by a name, parameters (optional), and a code block. It is called by
its name with arguments (if any).
Example:
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice"); // Output: Hello, Alice!
?>
2. Discuss function arguments and
default arguments in PHP with examples.
Answer:
- Arguments: Values passed to a function, defined in the function’s
parameter list.
- Default arguments: Parameters with preset values used if no argument
is provided.
Example:
<?php
function welcome($name, $greeting = "Hello") {
return "$greeting, $name!";
}
echo welcome("John"); // Output: Hello, John!
echo welcome("Jane", "Hi"); // Output: Hi, Jane!
?>
3. Explain variable-length
arguments in PHP with an example.
Answer: Variable-length arguments allow a function to accept any number
of arguments using the `...` (splat) operator, which collects arguments into an
array.
Example:
<?php
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3); // Output: 6
echo sum(10, 20, 30, 40); // Output: 100
?>
4. Discuss the `return` statement
and function variables in PHP with examples.
Answer:
- Return statement: Exits a function and sends a value back to the
caller. If omitted, the function returns `null`.
- Function variables: Variables defined within a function are local by
default, accessible only within that function unless returned or declared
global/static.
Example:
<?php
function calculateArea($length, $width) {
$area = $length * $width; // Local
variable
return $area; // Returns value
}
echo calculateArea(5, 3); // Output: 15
?>
=======================================================================
UNIT_III:- INTRODUCTION TO MYSQL :
1. What is MySQL?
Answer: MySQL is an open-source
relational database management system (RDBMS) based on Structured Query
Language (SQL). It is commonly used in web development.
---
2. Name any two storage engines supported by
MySQL.
Answer: InnoDB and MyISAM.
---
3. List any two MySQL data types.
Answer: `INT` for integers and
`VARCHAR` for variable-length strings.
---
4. What command is used to connect to a MySQL
database in PHP?
Answer: `mysqli_connect()` or using
PDO: `new PDO()`.
---
5. What does a JOIN do in SQL?
Answer: A JOIN combines rows from
two or more tables based on a related column.
---
6. What is the difference between
`mysqli_fetch_array()` and `mysqli_fetch_assoc()`?
Answer: `mysqli_fetch_array()`
returns both associative and numeric arrays, while `mysqli_fetch_assoc()`
returns only associative arrays.
---
7. How can you reference two tables in a SQL
query?
Answer: By using JOINs and
specifying table.column format. Example: `SELECT employees.name,
departments. name FROM employees JOIN departments ON employees.dept_id =
departments.id;`
---
8. Mention one benefit of integrating PHP with
MySQL.
Answer: It allows dynamic
data-driven websites and real-time interaction with databases.
---
LONG QUESTIONS (with Answers)
1. Explain the structure and syntax of MySQL.
Answer:
MySQL follows the SQL standard
syntax. Its structure includes:
- Statements like `SELECT`,
`INSERT`, `UPDATE`, `DELETE`.
- Clauses such as `WHERE`, `ORDER
BY`, `GROUP BY`.
- Expressions and predicates used
to form conditions.
Example Syntax:
SELECT name, age FROM students
WHERE age > 18 ORDER BY name;
This query selects names and ages
of students older than 18 and orders them alphabetically.
---
2. Differentiate between various types of
MySQL tables and storage engines.
Answer:
- InnoDB: Default engine, supports
transactions, row-level locking, foreign keys.
- MyISAM: Fast read operations, no
transaction support, table-level locking.
- MEMORY: Stores all data in RAM,
very fast but data is lost on server restart.
- CSV: Stores data in
comma-separated values, good for export/import.
Each engine has its use depending
on the application’s needs like speed, reliability, and data integrity.
---
3. Describe how to integrate PHP with MySQL.
Answer:
PHP can interact with MySQL using:
- MySQLi (MySQL Improved):
Procedural and OOP style
- PDO (PHP Data Objects): Offers a
consistent interface for multiple databases
Steps:
1. Connect to database using
`mysqli_connect()` or `new PDO()`
2. Write SQL queries
3. Execute queries
4. Fetch and display results
5. Close connection
Example:
$conn =
mysqli_connect("localhost", "root", "",
"mydb");
$result = mysqli_query($conn,
"SELECT * FROM users");
while($row =
mysqli_fetch_assoc($result)) {
echo $row['name'];
}
mysqli_close($conn);
---
4. Explain how to connect to a MySQL server
using PHP.
Answer:
Using `mysqli`:
$host = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
$conn = mysqli_connect($host,
$username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected
successfully!";
Using PDO:
try {
$conn = new PDO("mysql:host=localhost;dbname=testdb",
"root", "");
echo "Connected successfully!";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
---
5. How can PHP work with arrays of data from
MySQL?
Answer:
After fetching data from a MySQL
query, you can store it in an array using `mysqli_fetch_array()` or
`mysqli_fetch_assoc()`.
Example:
$result = mysqli_query($conn,
"SELECT * FROM products");
$products = [];
while($row =
mysqli_fetch_assoc($result)) {
$products[] = $row;
}
---
6. How to reference and join two tables in PHP
using MySQL?
Answer:
Suppose we have two tables:
`students` and `classes`.
SELECT students.name,
classes.class_name
FROM students
JOIN classes ON students.class_id =
classes.id;
In PHP:
$sql = "SELECT students.name,
classes.class_name
FROM students
JOIN classes ON students.class_id =
classes.id";
$result = mysqli_query($conn,
$sql);
while($row =
mysqli_fetch_assoc($result)) {
echo $row['name'] . " - " . $row['class_name'];
}
Short Questions and Answers
MySQL Structure and Syntax
1. What is the basic syntax for
creating a table in MySQL?
Answer: `CREATE TABLE table_name (column1 datatype, column2 datatype,
...);`
2. What is the purpose of the
`DESCRIBE` command in MySQL?
Answer: It displays the structure of a table, including column names,
data types, and constraints.
3. What is a primary key in MySQL?
Answer: A primary key is a unique identifier for each row in a table,
ensuring no duplicate values.
Types of MySQL Tables and Storage
Engines
4. Name two common MySQL storage
engines.
Answer: InnoDB and MyISAM.
5. What is the default storage
engine in MySQL 8.0?
Answer: InnoDB.
6. What is a temporary table in
MySQL?
Answer: A temporary table is a short-lived table that exists only for
the duration of a session and is automatically dropped when the session ends.
MySQL Commands
7. How do you select all records
from a table in MySQL?
Answer: `SELECT * FROM table_name;`
8. What does the `ALTER TABLE`
command do?
Answer: It modifies the structure of an existing table, such as adding
or dropping columns.
9. How do you delete a database in
MySQL?
Answer: `DROP DATABASE database_name;`
Integration of PHP with MySQL
10. What PHP function is used to
connect to a MySQL database?
Answer: `mysqli_connect()`
11. How do you close a MySQL
connection in PHP?
Answer: `mysqli_close($connection);`
12. What is the purpose of
`mysqli_query()` in PHP?
Answer: It executes a MySQL query on the database.
Connection to the MySQL Server
13. What are the parameters
required for `mysqli_connect()`?
Answer: Hostname, username, password, and database name.
14. What does the error `Access
denied for user` indicate?
Answer: It means the provided username or password is incorrect or the
user lacks permission.
Working with PHP and Arrays of Data
15. How do you fetch a row as an
associative array in PHP?
Answer: Use `mysqli_fetch_assoc($result);`
16. What is the purpose of
`mysqli_fetch_all()` in PHP?
Answer: It fetches all rows from a result set as an array.
Referencing Two Tables
17. What is a foreign key in MySQL?
Answer: A foreign key is a column that creates a relationship between
two tables by referencing the primary key of another table.
18. What is the purpose of the
`REFERENCES` keyword in MySQL?
Answer: It specifies the parent table and column for a foreign key
constraint.
Joining Two Tables in PHP
19. What is an `INNER JOIN` in
MySQL?
Answer: It returns only the rows where there is a match in both tables.
20. How do you perform a `LEFT
JOIN` in PHP with MySQL?
Answer: Use a query like: `SELECT * FROM table1 LEFT JOIN table2 ON
table1.id = table2.id;`
---
Long Questions and Answers
MySQL Structure and Syntax
1. Explain the structure of a MySQL
database and the basic syntax for creating and managing tables.
Answer:
A MySQL database is a structured collection of data organized into
tables, which consist of rows and columns. Each table is defined with a
specific structure, including column names, data types (e.g., INT, VARCHAR,
DATE), and constraints (e.g., PRIMARY KEY, FOREIGN KEY). The database is
managed using SQL (Structured Query Language).
Creating a Table:
The `CREATE TABLE` statement defines a new table. For example:
CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, username
VARCHAR(50) NOT NULL, email VARCHAR(100)
UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
Managing Tables:
- Alter Table: Modify structure, e.g., `ALTER TABLE users ADD phone
VARCHAR(15);` adds a phone column.
- Drop Table: Delete a table, e.g., `DROP TABLE users;`.
- Insert Data: `INSERT INTO users (username, email) VALUES ('john_doe',
'john@example.com');`.
- Query Data: `SELECT username, email FROM users WHERE id = 1;`.
This structure ensures data integrity and efficient querying.
Types of MySQL Tables and Storage
Engines
2. Discuss the different types of
MySQL storage engines and their use cases, focusing on InnoDB and MyISAM.
Answer:
MySQL supports multiple storage engines, each optimized for specific use
cases. A storage engine determines how data is stored, retrieved, and managed
in tables.
InnoDB:
- Features: Supports transactions, row-level locking, foreign key
constraints, and crash recovery.
- Use Cases: Ideal for applications requiring high reliability and
concurrency, such as e-commerce platforms, banking systems, or any system
needing ACID (Atomicity, Consistency, Isolation, Durability) compliance.
- Example: A table storing customer orders benefits from InnoDB’s
transaction support to ensure order and payment data are consistent.
- Default Engine: Since MySQL 5.5, InnoDB is the default engine.
MyISAM:
- Features: Supports table-level locking, full-text indexing, and is
simpler but lacks transactions and foreign key support.
- Use Cases: Suitable for read-heavy applications like data warehousing,
logging, or search systems where full-text search is needed.
- Example: A blog’s keyword search table might use MyISAM for its
full-text indexing capabilities.
Other Engines:
- Memory: Stores data in RAM for fast access, used for temporary or
cached data.
- Archive: Optimized for storing large amounts of historical data with
compression.
- CSV: Stores data in CSV format, useful for data exchange.
Choosing an Engine: Use InnoDB for transactional applications or when
data integrity is critical. Use MyISAM for read-heavy, non-transactional tasks.
The choice depends on performance, scalability, and feature requirements.
MySQL Commands
3. Describe the key MySQL commands
for database and table management, with examples of their usage.
Answer:
MySQL provides a range of commands for managing databases, tables, and
data. These commands fall under Data Definition Language (DDL), Data
Manipulation Language (DML), and Data Control Language (DCL).
Database Management:
- Create Database: `CREATE DATABASE company;`. Creates a new
database.
- Use Database: `USE company;`. Sets the active database.
- Drop Database: `DROP DATABASE company;`. Deletes the database and its
contents.
Table Management (DDL):
- Create Table:
CREATE TABLE employees (emp_id INT PRIMARY KEY, name VARCHAR(50),
department VARCHAR(30) );
Creates a table for employee data.
- Alter Table: `ALTER TABLE employees ADD salary DECIMAL(10,2);`. Adds a
salary column.
- Drop Table: `DROP TABLE employees;`. Deletes the table.
Data Manipulation (DML):
- Insert: `INSERT INTO employees (emp_id, name, department) VALUES (1,
'Alice', 'HR');`. Adds a record.
- Update: `UPDATE employees SET salary = 50000 WHERE emp_id = 1;`.
Modifies data.
- Delete: `DELETE FROM employees WHERE emp_id = 1;`. Removes a
record.
- Select: `SELECT name, department FROM employees WHERE salary >
40000;`. Retrieves data.
Data Control (DCL):
- Grant: `GRANT SELECT, INSERT ON company.* TO 'user'@'localhost';`.
Assigns permissions.
- Revoke: `REVOKE INSERT ON company.* FROM 'user'@'localhost';`. Removes
permissions.
These commands allow users to create, modify, query, and secure database
structures and data efficiently.
Integration of PHP with MySQL
4. Explain how PHP integrates with
MySQL, including the steps to connect, query, and handle results.
Answer:
PHP integrates with MySQL to create dynamic, data-driven web
applications. The `mysqli` (MySQL Improved) extension is commonly used for this
purpose. Below are the steps to connect, query, and handle results:
1. Connect to MySQL Server:
Use `mysqli_connect()` to establish a connection.
$host = "localhost";
$user = "root";
$password = "";
$database = "company";
$conn = mysqli_connect($host, $user, $password, $database);
if (!$conn) {
die("Connection failed: " .
mysqli_connect_error());
}
- Checks for connection errors and terminates if the connection
fails.
2. Execute a Query:
Use `mysqli_query()` to send SQL queries to the database.
$sql = "SELECT emp_id, name FROM employees WHERE department =
'HR'";
$result = mysqli_query($conn, $sql);
if (!$result) {
die("Query failed: " .
mysqli_error($conn));
}
- The query retrieves employees from the HR department.
3. Handle Results:
Fetch results using functions like `mysqli_fetch_assoc()`,
`mysqli_fetch_array()`, or `mysqli_fetch_all()`.
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row['emp_id'] .
", Name: " . $row['name'] . "<br>";
}
- Loops through the result set and displays each row as an associative
array.
4. Close the Connection:
Free resources and close the connection.
mysqli_free_result($result);
mysqli_close($conn);
Connection to the MySQL Server
5. Discuss the process of
connecting to a MySQL server using PHP, including error handling and security
considerations.
Answer:
Connecting to a MySQL server using PHP involves establishing a
communication channel between the PHP application and the MySQL database. The
`mysqli` extension is widely used for this purpose. Below is the process,
including error handling and security considerations:
Connection Process:
The `mysqli_connect()` function is used to connect to the MySQL server.
It requires four parameters: hostname, username, password, and database
name.
$host = "localhost";
$user = "root";
$password = "secure_password";
$database = "company";
$conn = mysqli_connect($host, $user, $password, $database);
Error Handling:
Check if the connection was successful and handle errors
gracefully.
if (!$conn) {
die("Connection failed: " .
mysqli_connect_error());
} else {
echo "Connected
successfully!";
}
Security Considerations:
- Credentials Management: Store sensitive data (e.g., username,
password) in environment variables or a configuration file outside the web root
(e.g., `.env` file).
$password = getenv('DB_PASSWORD'); // Using environment variable
- Use Secure Connections: Enable SSL/TLS for MySQL connections on remote
servers. Configure `mysqli_connect()` with SSL options:
$conn = mysqli_connect($host, $user, $password, $database, 3306, null,
MYSQLI_CLIENT_SSL);
- Prevent SQL Injection: Use prepared statements for queries instead of
concatenating user input into SQL strings.
- Limit Permissions: Grant the MySQL user only the necessary privileges
(e.g., `SELECT`, `INSERT`) for the specific database.
GRANT SELECT, INSERT ON company.* TO 'app_user'@'localhost' IDENTIFIED
BY 'secure_password';
- Close Connections: Always close the connection after use to free
resources.
mysqli_close($conn);
Example with Prepared Statement:
$stmt = mysqli_prepare($conn, "SELECT name FROM employees WHERE
emp_id = ?");
mysqli_stmt_bind_param($stmt, "i", $emp_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $name);
mysqli_stmt_fetch($stmt);
echo "Name: $name";
mysqli_stmt_close($stmt);
Working with PHP and Arrays of Data
6. How does PHP handle arrays of
data retrieved from MySQL, and what are the methods to process and display this
data?
Answer:
PHP retrieves data from MySQL as result sets, which can be converted
into arrays for processing. The `mysqli` extension provides several functions
to handle these arrays, enabling developers to process and display data
efficiently.
Retrieving Data as Arrays:
After executing a query with `mysqli_query()`, the result set can be
fetched as arrays using:
- mysqli_fetch_assoc(): Returns a row as an associative array (keys are
column names).
php
$result = mysqli_query($conn, "SELECT emp_id, name FROM
employees");
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row['emp_id']
. ", Name: " . $row['name'] . "<br>";
}
- mysqli_fetch_array(): Returns a row as an associative, numeric, or
both array types (controlled by `MYSQLI_ASSOC`, `MYSQLI_NUM`, or
`MYSQLI_BOTH`).
$row =
mysqli_fetch_array($result, MYSQLI_NUM); // Numeric keys: $row[0], $row[1]
- mysqli_fetch_all(): Fetches all rows as a multidimensional array
(requires MySQL Native Driver).
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($rows as $row) {
echo "ID: " . $row['emp_id']
. ", Name: " . $row['name'] . "<br>";
}
Processing Arrays:
- Looping: Use `foreach` or `while` to iterate over rows for display or
computation.
$total_salary = 0;
$result = mysqli_query($conn, "SELECT salary FROM employees");
while ($row = mysqli_fetch_assoc($result)) {
$total_salary += $row['salary'];
}
echo "Total Salary: $total_salary";
- Filtering: Use array functions like `array_filter()` to process
data.
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
$hr_employees = array_filter($rows, function($row) {
return $row['department'] == 'HR';
});
- Sorting: Sort arrays with `usort()` for custom sorting.
usort($rows, function($a, $b) {
return $a['name'] <=>
$b['name'];
});
Displaying Data:
- HTML Tables: Convert arrays into structured HTML output.
echo
"<table><tr><th>ID</th><th>Name</th></tr>";
foreach ($rows as $row) {
echo
"<tr><td>{$row['emp_id']}</td><td>{$row['name']}</td></tr>";
}
echo "</table>";
- JSON Output: Encode arrays as JSON for APIs.
header('Content-Type: application/json');
echo json_encode($rows);
Referencing Two Tables
7. Explain how to reference two
tables in MySQL using foreign keys, including an example of table creation and
data insertion.
Answer:
Referencing two tables in MySQL is achieved using foreign keys, which
establish a relationship between tables by linking a column in one table
(child) to the primary key of another table (parent). This ensures referential
integrity, meaning the child table’s foreign key values must match the parent
table’s primary key or be NULL (if allowed).
How Foreign Keys Work:
- A foreign key is defined in the child table and references the primary
key (or unique key) of the parent table.
- Foreign keys enforce constraints, such as preventing deletion of a
parent record if it’s referenced by a child record (unless `ON DELETE CASCADE`
is used).
- The parent table’s storage engine must support foreign keys (e.g.,
InnoDB).
Example: Creating and Using Related Tables:
Let’s create two tables: `departments` (parent) and `employees` (child),
with a foreign key linking them.
Step 1: Create the Parent Table (`departments`):
CREATE TABLE departments (dept_id INT PRIMARY KEY, dept_name VARCHAR(50) NOT NULL
) ENGINE=InnoDB;
Step 2: Create the Child Table (`employees`):
CREATE TABLE employees ( emp_id INT PRIMARY KEY, name VARCHAR(50),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES
departments(dept_id) ) ENGINE=InnoDB;
Step 3: Insert Data:
- Insert into the parent table first (since the child depends on
it).
INSERT INTO departments (dept_id, dept_name) VALUES (1, 'HR'), (2,
'Engineering');
- Insert into the child table, ensuring `dept_id` exists in
`departments`.
INSERT INTO employees (emp_id, name, dept_id) VALUES (101, 'Alice', 1),
(102, 'Bob', 2);
Step 4: Querying Related Data:
Use a `JOIN` to retrieve data from both tables:
SELECT e.name, d.dept_name
FROM employees e
JOIN departments d ON e.dept_id = d.dept_id;
Output:
name |
dept_name
------- |-----------
Alice | HR
Bob | Engineering
Benefits of Foreign Keys:
- Enforce data consistency.
- Simplify data integrity management.
- Enable relational queries with `JOIN`.
This approach ensures robust relationships between tables, critical for
relational database applications.
Joining Two Tables in PHP
8. Describe how to join two tables
in PHP using MySQL, including different types of joins and a code example.
Answer:
Joining two tables in PHP with MySQL involves executing a SQL `JOIN`
query to combine rows from two tables based on a related column (e.g., a
foreign key). PHP uses the `mysqli` extension to send the query and process the
results. Below, we discuss join types, their purposes, and provide a code
example.
Types of Joins:
- INNER JOIN: Returns rows where there is a match in both tables.
SELECT e.name, d.dept_name FROM employees e INNER JOIN departments d ON
e.dept_id = d.dept_id;
- Only includes employees with a valid department.
- LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table
(`employees`), with matching rows from the right table (`departments`).
Non-matching rows have NULL values for right table columns.
SELECT e.name, d.dept_name FROM employees e LEFT JOIN departments d ON
e.dept_id = d.dept_id;
- Includes employees even if they have no department (e.g., `dept_id` is
NULL).
- RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right
table (`departments`), with matching rows from the left table (`employees`).
Non-matching rows have NULL values for left table columns.
SELECT e.name, d.dept_name FROM employees e RIGHT JOIN departments d ON
e.dept_id = d.dept_id;
- Includes all departments, even those with no employees.
- FULL JOIN (or FULL OUTER JOIN): Returns all rows from both tables,
with NULLs for non-matching rows. MySQL does not directly support `FULL JOIN`,
but it can be simulated using `UNION` of `LEFT JOIN` and `RIGHT JOIN`.
PHP Code Example:
Assume two tables: `employees` (emp_id, name, dept_id) and `departments`
(dept_id, dept_name). The goal is to display employee names and their
department names using an `INNER JOIN`.
<?php
// Database connection
$host = "localhost";
$user = "root";
$password = "";
$database = "company";
$conn = mysqli_connect($host, $user, $password, $database);
if (!$conn) {
die("Connection failed: " .
mysqli_connect_error());
}
// SQL query with INNER JOIN
$sql = "SELECT e.name, d.dept_name
FROM employees e
INNER JOIN departments d ON
e.dept_id = d.dept_id";
$result = mysqli_query($conn, $sql);
if (!$result) {
die("Query failed: " .
mysqli_error($conn));
}
// Display results
echo "<table border='1'>";
echo "<tr><th>Employee
Name</th><th>Department</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" .
htmlspecialchars($row['name']) . "</td>";
echo "<td>" .
htmlspecialchars($row['dept_name']) . "</td></tr>";
}
echo "</table>";
// Clean up
mysqli_free_result($result);
mysqli_close($conn);
?>
Using Prepared Statements for
Joins:
To make the query dynamic (e.g., filter by department), use prepared
statements:
$dept_id = 1; // Example input
$stmt = mysqli_prepare($conn, "SELECT e.name, d.dept_name
FROM employees
e
INNER JOIN
departments d ON e.dept_id = d.dept_id
WHERE
d.dept_id = ?");
mysqli_stmt_bind_param($stmt, "i", $dept_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row['name'] .
", Dept: " . $row['dept_name'] . "<br>";
}
mysqli_stmt_close($stmt);
=======================================================================
UNIT-
IV:- WORKING WITH DATA and PHP FUNCTION:
Short Questions (with Answers)
- What
is the purpose of the <form> element in HTML?
The <form> element is used to collect user input and send it to a server for processing. - Name
three commonly used <input> types in HTML forms.
Text, Checkbox, Radio. - How
do you retrieve form data in PHP?
Using $_GET or $_POST superglobals depending on the form method. - What
does isset($_POST['submit']) do in PHP?
It checks whether the submit button has been clicked (i.e., if the form was submitted). - What
is a variable function in PHP?
A variable function is a function called using a variable holding the function's name: - $func =
"strlen";
- echo $func("Hello");
// Outputs 5
- Give
one example of a PHP string function.
strlen(), which returns the length of a string. - What
is the use of date() function in PHP?
It formats and displays the current date and time. - How
do you handle multiple checkboxes in a form?
Use name with square brackets name="hobbies[]" and handle as an array in PHP. - What
is explode() function used for?
It splits a string into an array using a delimiter. - What
does is_numeric() do?
It checks whether a variable is a number or a numeric string.
Long Questions (with Answers)
1. Explain how form data is
processed in PHP with an example.
Answer:
When a form is submitted, its data is sent to the server where it can be
processed using PHP.
Example:
<form method="POST"
action="process.php">
Name: <input type="text" name="username">
<input type="submit" name="submit">
</form>
In process.php:
if (isset($_POST['submit'])) {
$name = $_POST['username'];
echo "Hello, " . htmlspecialchars($name);
}
This captures user input and
prevents XSS using htmlspecialchars().
2. What are the different types of
input elements in HTML, and how are they handled in PHP?
Answer:
- Text: <input
type="text"> → $_POST['name']
- Checkbox: <input
type="checkbox" name="chk[]"> → An array $_POST['chk']
- Radio: <input
type="radio" name="gender"> → Only the selected
value is available
- Submit: <input
type="submit" name="submit"> → Used to detect form
submission
In PHP, all data is retrieved using
$_GET or $_POST.
3. How do you validate user input
in PHP?
Answer:
- Check
if the input exists
using isset() or empty().
- Sanitize
the input
using htmlspecialchars() or filter_var().
- Validate
format using
regular expressions or filter functions.
Example:
$email = $_POST['email'];
if (filter_var($email,
FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
} else {
echo "Invalid email";
}
4. Describe basic PHP functions
with examples:
Variable Function:
function greet() {
echo "Hello!";
}
$func = "greet";
$func(); // Calls greet()
String Function:
echo strtoupper("hello");
// Outputs: HELLO
Math Function:
echo pow(2, 3); // Outputs: 8
Date Function:
echo date("Y-m-d"); //
Outputs current date
Array Function:
$arr = [1, 2, 3];
array_push($arr, 4); // Adds 4 to
array
File Function:
$file = fopen("test.txt",
"r");
$content = fread($file,
filesize("test.txt"));
fclose($file);
Short Questions and Answers
FORM Elements and INPUT Elements
1. What is the purpose of the
`<form>` element in HTML?
Answer: The `<form>` element creates a container for input
elements, allowing users to submit data to a server for processing.
2. What is the difference between
the `GET` and `POST` methods in a form?
Answer: `GET` sends form data as URL parameters (visible, less secure,
limited data size), while `POST` sends data in the request body (more secure,
supports larger data).
3. What is the `name` attribute in
an `<input>` element used for?
Answer: The `name` attribute specifies the key used to identify the
input’s value when the form is submitted.
4. How do you create a text input
field in HTML?
Answer: `<input type="text" name="username">`
5. What does the `action` attribute
in a `<form>` tag do?
Answer: It specifies the URL or file (e.g., `process.php`) where the
form data is sent for processing.
Processing the Form
6. How do you access form data in
PHP sent via `POST`?
Answer: Use the `$_POST` superglobal array, e.g., `$username =
$_POST['username'];`.
7. What is the purpose of
`htmlspecialchars()` when processing form data?
Answer: It converts special characters to HTML entities to prevent XSS
(cross-site scripting Attacks.
8. How can you check if a form has
been submitted in PHP?
Answer: Check if a submit button’s `name` exists in `$_POST`, e.g., `if
(isset($_POST['submit']))`.
User Input and Validation
9. What is the `required` attribute
in an `<input>` element?
Answer: It ensures the input field must be filled before the form can be
submitted.
10. How do you validate that a user
input is not empty in PHP?
Answer: Use `empty()` or `isset()`, e.g., `if
(empty($_POST['username'])) { echo "Username is required"; }`.
11. What PHP function checks if a
string is a valid email format?
Answer: `filter_var($email, FILTER_VALIDATE_EMAIL)`.
Checkbox and Radio Inputs
12. How do you create a checkbox
input in HTML?
Answer: `<input type="checkbox" name="hobby"
value="reading">`.
13. How do you process multiple
checkbox values in PHP?
Answer: Use an array in the `name` attribute, e.g., `<input
type="checkbox" name="hobbies[]">`, and access via
`$_POST['hobbies']`.
14. What is the difference between
a checkbox and a radio input?
Answer: Checkboxes allow multiple selections; radio inputs allow only
one selection within a group.
15. How do you group radio buttons
in a form?
Answer: Use the same `name` attribute for all radio buttons in the
group, e.g., `<input type="radio" name="gender"
value="male">`.
Multiple Submit Buttons and
Processing
16. How can a form have multiple
submit buttons?
Answer: Use different `name` or `value` attributes for each submit
button, e.g., `<input type="submit" name="action"
value="Save">` and `<input type="submit"
name="action" value="Delete">`.
17. How do you determine which
submit button was clicked in PHP?
Answer: Check the `name` or `value` in `$_POST`, e.g., `if
($_POST['action'] === 'Save')`.
Basic Input Testing and Dynamic
Page Title
18. How do you test if a user input
is numeric in PHP?
Answer: Use `is_numeric()`, e.g., `if (is_numeric($_POST['age']))`.
19. How can you set a dynamic page
title in PHP?
Answer: Use a variable in the `<title>` tag, e.g., `<?php
$title = "Welcome, " . $_POST['username']; ?>
<title><?php echo $title; ?></title>`.
String and Array Manipulation
20. How do you treat a string as an
array in PHP?
Answer: Access characters using square brackets, e.g., `$str =
"Hello"; echo $str[0]; // Outputs: H`.
21. How do you add an item to an
array in PHP?
Answer: Use `array_push()` or the `[]` operator, e.g., `$arr[] =
"new item";`.
22. What PHP function splits a
string into an array?
Answer: `explode()`, e.g., `$array = explode(",",
"apple,banana,orange");`.
Basic PHP Functions
23. What is a variable function in
PHP?
Answer: A function whose name is stored in a variable and called
dynamically, e.g., `$func = "strlen"; echo $func("Hello");
// Outputs: 5`.
24. What does the `strlen()`
function do?
Answer: Returns the length of a string, e.g., `strlen("Hello")
// Returns: 5`.
25. What is the purpose of the
`abs()` math function?
Answer: Returns the absolute (positive) value of a number, e.g.,
`abs(-5) // Returns: 5`.
26. How do you get the current date
in PHP?
Answer: Use `date()`, e.g., `echo date("Y-m-d"); // Outputs:
2025-04-20`.
27. What does the `array_merge()`
function do?
Answer: Combines two or more arrays into one, e.g., `$merged =
array_merge([1, 2], [3, 4]); // Returns: [1, 2, 3, 4]`.
28. How do you read a file’s
contents in PHP?
Answer: Use `file_get_contents()`, e.g., `$content =
file_get_contents("file.txt");`.
---
Long Questions and Answers
FORM Elements and Processing
1. Explain how to create an HTML
form with text, checkbox, and radio inputs, and process it in PHP, including
basic validation.
Answer:
Create an HTML form:
<form
action="process.php" method="post">
<label>Username: <input
type="text" name="username"
required></label><br>
<label>Hobbies:
<input type="checkbox"
name="hobbies[]" value="reading"> Reading
<input type="checkbox"
name="hobbies[]" value="gaming"> Gaming
</label><br>
<label>Gender:
<input type="radio"
name="gender" value="male" required> Male
<input type="radio"
name="gender" value="female"> Female
</label><br>
<input type="submit"
name="submit" value="Submit">
</form>
Process in `process.php`:
<?php
if (isset($_POST['submit'])) {
// Sanitize and validate username
$username =
htmlspecialchars($_POST['username']);
if (empty($username)) {
echo "Username is
required.";
exit;
}
// Process hobbies (checkboxes)
$hobbies = isset($_POST['hobbies']) ?
$_POST['hobbies'] : [];
if (empty($hobbies)) {
echo "Please select at least
one hobby.";
exit;
}
// Process gender (radio)
$gender = $_POST['gender'] ?? '';
if (empty($gender)) {
echo "Please select a
gender.";
exit;
}
// Output results
echo "Username:
$username<br>";
echo "Hobbies: " .
implode(", ", $hobbies) . "<br>";
echo "Gender: $gender";
}
?>
This form collects a username, multiple hobbies, and a single gender
selection, validates inputs, and displays sanitized results.
2. How can you handle multiple
submit buttons in a single form and process them differently in PHP? Provide an
example.
Answer:
Use distinct `name` or `value` attributes for submit buttons and check
their values in PHP.
Example HTML form:
<form
action="process.php" method="post">
<label>Name: <input
type="text" name="name"></label><br>
<input type="submit"
name="action" value="Save">
<input type="submit"
name="action" value="Delete">
</form>
Process in `process.php`:
<?php
if (isset($_POST['action'])) {
$name =
htmlspecialchars($_POST['name']);
$action = $_POST['action'];
switch ($action) {
case 'Save':
echo "Saving $name to the
database.";
break;
case 'Delete':
echo "Deleting $name from
the database.";
break;
default:
echo "Invalid
action.";
}
}
?>
User Input and Validation
3. Describe how to validate user
input from a form in PHP, including checks for empty fields, email format, and
numeric values.
Answer:
Validation ensures user input is safe and meets requirements.
Example:
<form action="validate.php" method="post">
<label>Email: <input
type="email" name="email"></label><br>
<label>Age: <input
type="text" name="age"></label><br>
<input type="submit"
name="submit" value="Submit">
</form>
Process in `validate.php`:
<?php
if (isset($_POST['submit'])) {
// Sanitize inputs
$email = filter_var($_POST['email'],
FILTER_SANITIZE_EMAIL);
$age = filter_var($_POST['age'],
FILTER_SANITIZE_NUMBER_INT);
// Validate email
if (empty($email)) {
echo "Email is
required.<br>";
} elseif (!filter_var($email,
FILTER_VALIDATE_EMAIL)) {
echo "Invalid email
format.<br>";
}
// Validate age
if (empty($age)) {
echo "Age is
required.<br>";
} elseif (!is_numeric($age) || $age <
0) {
echo "Age must be a positive
number.<br>";
} else {
echo "Valid input: Email =
$email, Age = $age";
}
}
?>
This script sanitizes inputs, checks for empty fields, validates email
format, and ensures age is a positive number.
Dynamic Page Title and String
Manipulation
4. How can you create a dynamic
page title based on user input and manipulate the input string as an array in
PHP? Provide an example.
Answer:
Use user input to set the `<title>` tag and treat the string as an
array for manipulation.
Example:
<form action="title.php" method="post">
<label>Enter your name: <input
type="text" name="name"></label><br>
<input type="submit"
name="submit" value="Submit">
</form>
Process in `title.php`:
<?php
$title = "Welcome";
if (isset($_POST['submit']) && !empty($_POST['name'])) {
$name =
htmlspecialchars($_POST['name']);
$title = "Welcome, $name";
// Treat string as array
$nameArray = str_split($name);
echo "Characters in your name:
" . implode(", ", $nameArray);
}
?>
<html>
<head>
<title><?php echo $title;
?></title>
</head>
<body>
<h1><?php echo $title;
?></h1>
</body>
</html>
The script sets a dynamic title and splits the name into an array of
characters for display.
Basic PHP Functions
5. Explain the use of Variable,
String, Math, Date, Array, and File functions in PHP with a practical example
combining them.
Answer:
These functions handle different data types and operations. Example: A
script that processes user data, manipulates strings, performs calculations,
and logs to a file.
<?php
// Variable function
$func = "strlen";
$username = "JohnDoe";
echo "Username length: " . $func($username) .
"<br>"; // String function
// String function
$uppercase = strtoupper($username);
echo "Uppercase username: $uppercase<br>";
// Math function
$random = rand(1, 100);
echo "Random number: $random<br>";
// Date function
$date = date("Y-m-d H:i:s");
echo "Current date: $date<br>";
// Array function
$users = ["Alice", "Bob", $username];
$users = array_merge($users, ["Charlie"]);
echo "Users: " . implode(", ", $users) .
"<br>";
// File function
$log = "User: $username, Date: $date, Random: $random\n";
file_put_contents("log.txt", $log, FILE_APPEND);
echo "Data logged to file.";
?>
=======================================================================
UNIT
-V- WORKING WITH DATABASE AND PHP FUNCTION:
SHORT QUESTIONS AND ANSWERS
Q1. How do you create a table in
MySQL using PHP?
A:
You use the CREATE TABLE SQL command within a PHP mysqli_query() function.
Example:
$sql = "CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY, name
VARCHAR(100),
email VARCHAR(100))";
mysqli_query($conn, $sql);
Q2. How can you insert data into a
MySQL table using PHP?
A:
$sql = "INSERT INTO users
(name, email) VALUES ('John Doe', 'john@example.com')";
mysqli_query($conn, $sql);
Q3. Which PHP function is used to
connect to MySQL?
A: mysqli_connect()
Example:
$conn =
mysqli_connect("localhost", "username",
"password", "database");
Q4. How do you delete a record from
a table using PHP?
A:
$sql = "DELETE FROM users
WHERE id = 1";
mysqli_query($conn, $sql);
Q5. How can you display data from a
MySQL table using PHP?
A:
$result = mysqli_query($conn,
"SELECT * FROM users");
while($row =
mysqli_fetch_assoc($result)) {
echo $row['name'] . "<br>";
}
Q6. What function is used to fetch
rows from a query result?
A: mysqli_fetch_assoc()
Q7. How can you add a link to edit
a specific row in the table?
A:
echo "<a
href='edit.php?id=" . $row['id'] . "'>Edit</a>";
LONG QUESTIONS AND ANSWERS
Q1. Explain the steps to create and
manipulate a MySQL table using PHP.
A:
- Connect
to the Database:
$conn =
mysqli_connect("localhost", "root", "",
"myDB");
- Create
a Table:
$sql = "CREATE TABLE users ( id
INT AUTO_INCREMENT PRIMARY KEY, name
VARCHAR(100),
email VARCHAR(100))";
mysqli_query($conn, $sql);
- Insert
Data into Table:
$sql = "INSERT INTO users
(name, email) VALUES ('Alice', 'alice@example.com')";
mysqli_query($conn, $sql);
- Update
Data in Table:
$sql = "UPDATE users SET email
= 'new@example.com' WHERE name = 'Alice'";
mysqli_query($conn, $sql);
- Delete
Data from Table:
$sql = "DELETE FROM users
WHERE name = 'Alice'";
mysqli_query($conn, $sql);
Q2. Write a PHP script to display
data from a table with edit and delete links for each row.
A:
$conn =
mysqli_connect("localhost", "root", "",
"myDB");
$result = mysqli_query($conn,
"SELECT * FROM users");
echo "<table
border='1'>";
echo
"<tr><th>Name</th><th>Email</th><th>Actions</th></tr>";
while($row =
mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>
<a href='edit.php?id=" .
$row['id'] . "'>Edit</a> |
<a
href='delete.php?id=" . $row['id'] . "'>Delete</a>
</td>";
echo "</tr>";
}
echo "</table>";
Q3. How can you edit and update
data in a MySQL table using a PHP form?
A:
- Fetch
data to pre-fill the form:
$id = $_GET['id'];
$result = mysqli_query($conn,
"SELECT * FROM users WHERE id=$id");
$row = mysqli_fetch_assoc($result);
- HTML
Form:
<form
method="POST">
<input type="text" name="name"
value="<?php echo $row['name']; ?>">
<input type="email" name="email"
value="<?php echo $row['email']; ?>">
<input type="submit" name="update"
value="Update">
</form>
- Update
Logic:
if(isset($_POST['update'])) {
$name = $_POST['name'];
$email = $_POST['email'];
mysqli_query($conn, "UPDATE users SET name='$name', email='$email'
WHERE id=$id");
}
Short Questions and Answers
1. How do you create a table in a
MySQL database using PHP?
Answer: Use the `CREATE TABLE` SQL
statement with PHP's `mysqli` or `PDO` extension.
$conn = new
mysqli("localhost", "username", "password",
"database");
$sql = "CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY, name
VARCHAR(50),
email VARCHAR(100))";
if ($conn->query($sql) === TRUE)
{
echo "Table created successfully";
} else {
echo "Error: " . $conn->error;
}
$conn->close();
2. How can you insert a record into
a table using PHP?
Answer: Use the `INSERT INTO` SQL
statement.
$conn = new
mysqli("localhost", "username", "password",
"database");
$sql = "INSERT INTO users
(name, email) VALUES ('John Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE)
{
echo "Record inserted successfully";
} else {
echo "Error: " . $conn->error;
}
$conn->close();
3. How do you display data from a
table in PHP?
Answer: Use `SELECT` to fetch data
and loop through the result.
$conn = new
mysqli("localhost", "username", "password",
"database");
$result =
$conn->query("SELECT * FROM users");
while ($row =
$result->fetch_assoc()) {
echo "ID: " . $row['id'] . ", Name: " . $row['name']
. ", Email: " . $row['email'] . "<br>";
}
$conn->close();
4. How do you delete a record from
a table in PHP?
Answer: Use the `DELETE` SQL
statement with a condition.
$conn = new
mysqli("localhost", "username", "password",
"database");
$sql = "DELETE FROM users
WHERE id = 1";
if ($conn->query($sql) === TRUE)
{
echo "Record deleted successfully";
} else {
echo "Error: " . $conn->error;
}
$conn->close();
5. How do you add a link to a table
cell in PHP?
Answer: Include an HTML anchor tag
in the table output.
echo "<td><a
href='edit.php?id=" . $row['id'] .
"'>Edit</a></td>";
6. How do you edit a record in a
table using PHP?
Answer: Use the `UPDATE` SQL
statement with a condition.
$conn = new
mysqli("localhost", "username", "password",
"database");
$sql = "UPDATE users SET name
= 'Jane Doe', email = 'jane@example.com' WHERE id = 1";
if ($conn->query($sql) === TRUE)
{
echo "Record updated successfully";
} else {
echo "Error: " . $conn->error;
}
$conn->close();
7. How do you fill a table with
sample data in PHP?
Answer: Use multiple `INSERT INTO`
statements or a loop.
$conn = new
mysqli("localhost", "username", "password",
"database");
$users = [
['Alice', 'alice@example.com'],
['Bob', 'bob@example.com']
];
foreach ($users as $user) {
$sql = "INSERT INTO users (name, email) VALUES ('$user[0]',
'$user[1]')";
$conn->query($sql);
}
echo "Data inserted
successfully";
$conn->close();
8. How do you manipulate a table
structure in PHP?
Answer: Use `ALTER TABLE` to modify
columns or constraints.
$conn = new
mysqli("localhost", "username", "password",
"database");
$sql = "ALTER TABLE users ADD
phone VARCHAR(15)";
if ($conn->query($sql) === TRUE)
{
echo "Table modified successfully";
} else {
echo "Error: " . $conn->error;
}
$conn->close();
---
Long Questions and Answers
1. Explain how to create a table,
insert data, and display it in a formatted HTML table with edit and delete
links using PHP and MySQL.
Answer:
To accomplish this, you need to
connect to a MySQL database, create a table, insert data, and display it in an
HTML table with links for editing and deleting records. Below is a step-by-step
example:
<?php
// Database connection
$conn = new
mysqli("localhost", "username", "password",
"database");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create table
$sql = "CREATE TABLE IF NOT
EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50), email VARCHAR(100))";
$conn->query($sql);
// Insert sample data
$sql = "INSERT INTO users
(name, email) VALUES ('John Doe',
'john@example.com'),
('Jane Smith', 'jane@example.com')";
$conn->query($sql);
// Display data in HTML table
$result =
$conn->query("SELECT * FROM users");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>";
while ($row =
$result->fetch_assoc()) {
echo "<tr>
<td>" . $row['id'] .
"</td>
<td>" . $row['name'] .
"</td>
<td>" . $row['email'] .
"</td>
<td>
<a href='edit.php?id=" .
$row['id'] . "'>Edit</a> |
<a href='delete.php?id=" .
$row['id'] . "' onclick='return confirm(\"Are you
sure?\")'>Delete</a>
</td>
</tr>";
}
echo "</table>";
$conn->close();
?>
---
2. How would you implement a PHP
script to add new data to a table via a form, edit existing data, and delete
records securely using prepared statements?
Answer:
This involves creating a form for
adding data, a form for editing data, and a script for deleting records, all
using prepared statements for security. Below is an example implementation:
add.php (Form and Insert):
<?php
$conn = new
mysqli("localhost", "username", "password",
"database");
if
($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
// Prepared statement for insertion
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES
(?, ?)");
$stmt->bind_param("ss", $name, $email);
if ($stmt->execute()) {
echo "Record added
successfully";
} else {
echo "Error: " .
$stmt->error;
}
$stmt->close();
}
$conn->close();
?>
<form
method="post">
Name: <input type="text" name="name"
required><br>
Email: <input type="email" name="email"
required><br>
<input type="submit" value="Add User">
</form>
edit.php (Form and Update):
<?php
$conn = new
mysqli("localhost", "username", "password",
"database");
$id = $_GET['id'];
// Fetch record
$stmt =
$conn->prepare("SELECT name, email FROM users WHERE id = ?");
$stmt->bind_param("i",
$id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$stmt->close();
if
($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
// Prepared statement for update
$stmt = $conn->prepare("UPDATE users SET name = ?, email = ?
WHERE id = ?");
$stmt->bind_param("ssi", $name, $email, $id);
if ($stmt->execute()) {
echo "Record updated
successfully";
} else {
echo "Error: " .
$stmt->error;
}
$stmt->close();
}
$conn->close();
?>
<form
method="post">
Name: <input type="text" name="name"
value="<?php echo $row['name']; ?>" required><br>
Email: <input type="email" name="email"
value="<?php echo $row['email']; ?>" required><br>
<input type="submit" value="Update User">
</form>
delete.php (Delete Record):
<?php
$conn = new
mysqli("localhost", "username", "password",
"database");
$id = $_GET['id'];
// Prepared statement for deletion
$stmt =
$conn->prepare("DELETE FROM users WHERE id = ?");
$stmt->bind_param("i",
$id);
if ($stmt->execute()) {
echo "Record deleted successfully";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
$conn->close();
header("Location:
index.php"); // Redirect to main page
exit;
?>
---
3. Describe how to manipulate a
table structure, fill it with data, and display the new information in PHP,
including error handling.
Answer:
Manipulating a table structure
involves altering its schema (e.g., adding columns). Filling it with data
involves inserting records, and displaying the new information requires
fetching and formatting the data. Below is an example with error handling:
<?php
$conn = new
mysqli("localhost", "username", "password",
"database");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
try {
// Manipulate table structure (add a column)
$sql = "ALTER TABLE users ADD age INT NULL";
if (!$conn->query($sql)) {
throw new Exception("Error
modifying table: " . $conn->error);
}
echo "Table structure modified successfully<br>";
// Fill table with data
$stmt = $conn->prepare("INSERT INTO users (name, email, age)
VALUES (?, ?, ?)");
$users = [
['Alice', 'alice@example.com', 25],
['Bob', 'bob@example.com', 30]
];
foreach ($users as $user) {
$stmt->bind_param("ssi",
$user[0], $user[1], $user[2]);
if (!$stmt->execute()) {
throw new Exception("Error
inserting data: " . $stmt->error);
}
}
echo "Data inserted successfully<br>";
$stmt->close();
// Display new information
$result = $conn->query("SELECT * FROM users");
if (!$result) {
throw new Exception("Error
fetching data: " . $conn->error);
}
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Age</th>
</tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr>
<td>" . $row['id'] .
"</td>
<td>" . $row['name'] .
"</td>
<td>" . $row['email'] .
"</td>
<td>" . ($row['age'] ??
'N/A') . "</td>
</tr>";
}
echo "</table>";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
$conn->close();
}
?>
==================================================================
0 Comments