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

PHP_QB

The document provides a comprehensive overview of various PHP concepts including object cloning, introspection, serialization, method overriding, magic methods, constructors and destructors, inheritance types, interfaces, traits, and HTTP methods (GET and POST). It includes code examples to illustrate each concept, demonstrating how to implement and utilize these features in PHP programming. Additionally, it discusses the differences between sessions and cookies, emphasizing the importance of sessions in managing user data across multiple pages.

Uploaded by

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

PHP_QB

The document provides a comprehensive overview of various PHP concepts including object cloning, introspection, serialization, method overriding, magic methods, constructors and destructors, inheritance types, interfaces, traits, and HTTP methods (GET and POST). It includes code examples to illustrate each concept, demonstrating how to implement and utilize these features in PHP programming. Additionally, it discusses the differences between sessions and cookies, emphasizing the importance of sessions in managing user data across multiple pages.

Uploaded by

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

Chapter 3 (CO 3)

• Write a program for cloning of an object.


Ans.

PHP has a built-in clone keyword used for object cloning. By default, it creates a shallow copy, but you
can control cloning behavior using the __clone() magic method.

program:
<?php

class Person {

public $name;

public $age;

// Original object

$p1 = new Person();

$p1->name = "Alice";

$p1->age = 30;

// Clone the object

$p2 = clone $p1;

// Change cloned object's data

$p2->name = "Bob";

$p2->age = 25;

// Print both objects

echo "Original: $p1->name, $p1->age\n";


echo "Cloned: $p2->name, $p2->age\n";

?>

2.Define Introspection and explain methods of it with suitable example.

Ans.

Introspection in PHP means the ability of a program to examine itself — specifically, to


inspect classes, interfaces, functions, methods, and properties at runtime.

It’s useful for debugging, frameworks, object manipulation, and more.

Here are some of the most commonly used introspection methods:

Example:

<?php

class Person {
public $name = "Alice";
public $age = 30;

public function greet() {


echo "Hello, I'm $this->name\n";
}

private function secret() {


echo "This is private!";
}
}

// Create object
$p = new Person();

// Introspection examples
echo "Class Name: " . get_class($p) . "\n";

echo "Methods:\n";
print_r(get_class_methods($p));

echo "Class Properties:\n";


print_r(get_class_vars('Person'));

echo "Object Properties:\n";


print_r(get_object_vars($p));

echo "Does method 'greet' exist? ";


echo method_exists($p, 'greet') ? "Yes\n" : "No\n";

echo "Does property 'age' exist? ";


echo property_exists($p, 'age') ? "Yes\n" : "No\n";

?>

Output:

Class Name: Person


Methods:
Array
(
[0] => greet
[1] => secret
)
Class Properties:
Array
(
[name] => Alice
[age] => 30
)
Object Properties:
Array
(
[name] => Alice
[age] => 30
)
Does method 'greet' exist? Yes
Does property 'age' exist? Yes

3. Explain the concept of Serialization with example.

Ans.

Serialization is the process of converting a PHP object or variable into a string format, so
it can be:

• Stored in a file or database

• Sent over a network

• Saved in a session

Later, it can be restored back to its original form using unserialization.

Functions Used:

serialize() → Converts a variable/object to a storable string.

unserialize() → Converts it back to the original form.

✅ Example:
<?php

class Person {
public $name;
public $age;
}

// Create an object
$p1 = new Person();
$p1->name = "Alice";
$p1->age = 30;
// Serialize the object
$serializedData = serialize($p1);
echo "Serialized: " . $serializedData . "\n";

// Unserialize the object


$p2 = unserialize($serializedData);
echo "Unserialized: Name = " . $p2->name . ", Age = " . $p2->age . "\n";

?>

Output:

Serialized: O:6:"Person":2:{s:4:"name";s:5:"Alice";s:3:"age";i:30;}
Unserialized: Name = Alice, Age = 30

Note:

PHP can only serialize data types it understands (objects, arrays, strings, etc.).

If your class has resources like file handles or database connections, they won’t serialize
properly.

4. Explain the concept of overriding in detail.

Ans.

Overriding means redefining a parent class method in a child class with the same method
name, so the child class can provide its own specific behavior.

It is a core concept of Object-Oriented Programming (OOP) and allows for runtime


polymorphism.

✅ When to Use Overriding:


When a child class needs to change or extend the behavior of a method defined in the
parent class.

Key Rules of Overriding in PHP:

Method name must be the same in both classes.

The child class overrides the parent class’s method.


Access modifiers must be compatible (e.g., cannot reduce visibility).

✅ Example:

<?php

class Animal {
public function sound() {
echo "Animals make sound\n";
}
}

class Dog extends Animal {


// Overriding the sound() method
public function sound() {
echo "Dog barks\n";
}
}

class Cat extends Animal {


// Overriding the sound() method
public function sound() {
echo "Cat meows\n";
}
}

// Test
$dog = new Dog();
$cat = new Cat();

$dog->sound(); // Output: Dog barks


$cat->sound(); // Output: Cat meows

?>

💡 Why is Overriding Important?

• Helps in code reuse and customization.



• Supports polymorphism.

• Makes your code more modular and flexible.
5. Elaborate the following: i) __call() and __callstatic()[Or Method Overloading]

Ans.

📌 What is Method Overloading?


In other languages like Java or C++, method overloading means defining multiple
methods with the same name but different parameters.

But in PHP, real method overloading is not supported directly. Instead, PHP provides
magic methods to mimic this behavior:

✨ __call() Magic Method:

Triggered when calling non-existent or inaccessible object methods.

Syntax:

public function __call($name, $arguments)

Parameters:

$name: Name of the method being called.

$arguments: Array of arguments passed to the method.

✨ __callStatic() Magic Method:

Similar to __call(), but triggered when calling non-existent static methods.

Syntax:

public static function __callStatic($name, $arguments)

✅ Example:

<?php

class MagicMethods {
// Called for undefined object methods
public function __call($name, $arguments) {
echo "Calling object method '$name' with arguments: ";
print_r($arguments);
}

// Called for undefined static methods


public static function __callStatic($name, $arguments) {
echo "Calling static method '$name' with arguments: ";
print_r($arguments);
}
}

$obj = new MagicMethods();

// Object method call (non-existent)


$obj->greet("Alice", 25);

// Static method call (non-existent)


MagicMethods::sayHello("Bob");

?>

Output:

Calling object method 'greet' with arguments: Array ( [0] => Alice [1] => 25 )
Calling static method 'sayHello' with arguments: Array ( [0] => Bob )

💡 Use Cases:

Creating flexible APIs or dynamic behaviors.

Handling multiple method arguments dynamically.

Making frameworks and libraries more user-friendly.

Notes:

These magic methods only trigger when the method does not exist or is not accessible.

Should be used carefully to avoid confusion or bugs.

6. Define constructor and Destructor with example.

Ans.
🔨 Constructor in PHP:

A constructor is a special method in a class that is automatically called when an object is


created. It is commonly used to initialize object properties.

✅ Syntax:

public function __construct() {


// Initialization code
}

💥 Destructor in PHP
A destructor is a special method that is automatically called when the object is destroyed
or the script ends. It is used to clean up resources, like closing files or database
connections.

✅ Syntax:

public function __destruct() {


// Cleanup code
}

✅ Example:

<?php

class Person {
public $name;

// Constructor
public function __construct($name) {
$this->name = $name;
echo "Constructor called. Hello, $this->name!\n";
}

// Destructor
public function __destruct() {
echo "Destructor called. Goodbye, $this->name!\n";
}
}
// Creating an object
$p = new Person("Alice");

// Do something
echo "Object is being used...\n";

?>

output:

Constructor called. Hello, Alice!


Object is being used...
Destructor called. Goodbye, Alice!

Notes:

Constructor runs automatically when the object is created.

Destructor runs automatically when:

The object goes out of scope.

The script ends.

You can pass parameters to constructors but not to destructors.

7. Explain types of constructor with example

Ans.

🔨 What is a Constructor?
A constructor is a special method that gets automatically called when a new object is
created. It is used to initialize properties of a class.

Types of Constructors in PHP


Though PHP does not officially classify constructors like some other languages (e.g., C++
or Java), we can logically divide them into 3 main types:

1. Default Constructor
2. Parameterized Constructor
3. Constructor with Default Arguments (Simulated Overloading)
1. Default Constructor
A constructor that takes no parameters.

Ex:
<?php

class Car {
public function __construct() {
echo "Default constructor called.\n";
}
}

2. Parameterized Constructor
A constructor that accepts arguments to initialize the object.

Ex:

<?php

class Car {
public $brand;
public $model;

public function __construct($brand, $model) {


$this->brand = $brand;
$this->model = $model;
echo "Car: $this->brand $this->model\n";
}
}

$car1 = new Car("Toyota", "Corolla");

?>

3. Constructor with Default Arguments (Simulated Overloading)


PHP doesn't support multiple constructors (method overloading), but you can simulate it
using default parameters.

Ex:

<?php

class Car {
public $brand;
public function __construct($brand = "Default Brand") {
$this->brand = $brand;
echo "Brand: $this->brand\n";
}
}

$car1 = new Car(); // Uses default value


$car2 = new Car("Nissan"); // Uses passed value

?>

$car1 = new Car();

?>

8. Define inheritance and its types

Ans

What is Inheritance in PHP?

Inheritance is an Object-Oriented Programming (OOP) concept where a child class (also


called a derived or subclass) inherits properties and methods from a parent class (also
called a base or superclass).

✅ Why Use Inheritance?

Code Reusability

Easier Maintenance

Logical Grouping

Types of Inheritance in PHP

PHP supports the following types of inheritance:


Multiple Inheritance in PHP?
PHP does not support multiple inheritance (one class extending more than one class).
But you can achieve similar functionality using Traits.

9. Explain single, Multilevel, Hierarchical inheritance with example

Ans..

1. Single Inheritance

Definition:
A child class inherits from one parent class.

🔹 Example:

<?php

class Animal {
public function eat() {
echo "Animal is eating.\n";
}
}

class Dog extends Animal {


public function bark() {
echo "Dog is barking.\n";
}
}
$dog = new Dog();
$dog->eat(); // Inherited method
$dog->bark(); // Own method

?>

2. Multilevel Inheritance

Definition:
A class inherits from a child class, forming a chain (grandparent → parent → child).

🔹 Example:

<?php

class Animal {
public function eat() {
echo "Animal is eating.\n";
}
}

class Dog extends Animal {


public function bark() {
echo "Dog is barking.\n";
}
}

class Puppy extends Dog {


public function weep() {
echo "Puppy is weeping.\n";
}
}

$puppy = new Puppy();


$puppy->eat(); // Grandparent class method
$puppy->bark(); // Parent class method
$puppy->weep(); // Own method

?>

3. Hierarchical Inheritance
Definition:
Multiple classes inherit from the same parent class.

🔹 Example:

<?php

class Animal {
public function eat() {
echo "Animal is eating.\n";
}
}

class Dog extends Animal {


public function bark() {
echo "Dog is barking.\n";
}
}

class Cat extends Animal {


public function meow() {
echo "Cat is meowing.\n";
}
}

$dog = new Dog();


$cat = new Cat();

$dog->eat(); // Inherited from Animal


$dog->bark(); // Dog's own

$cat->eat(); // Inherited from Animal


$cat->meow(); // Cat's own

?>

10. How multiple inheritance is achieved in PHP or Explain interface with example.

Ans.
How is Multiple Inheritance achieved in PHP?
🔴 Problem:
PHP does not support multiple inheritance directly through classes — meaning, a class
cannot extend more than one class.

What is an Interface in PHP?


An interface defines a set of method signatures (without body) that a class must
implement.

• Helps in achieving multiple inheritance



• Supports polymorphism

Syntax:

interface InterfaceName {
public function method1();
}

🔹 Example:

<?php

interface Logger {
public function log($message);
}

interface Printer {
public function printData($data);
}

class Machine implements Logger, Printer {


public function log($message) {
echo "Logging: $message\n";
}

public function printData($data) {


echo "Printing: $data\n";
}
}
What is a Trait in PHP?

A Trait is a mechanism for reusing code in multiple classes in PHP. Traits help overcome
PHP’s limitation of no multiple class inheritance.

Traits can contain methods and properties.

A class can use multiple traits.

Traits are included using the use keyword.

// Testing
$machine = new Machine();
$machine->log("Start machine");
$machine->printData("Document.pdf");

?>

✅ Syntax of Trait:

trait TraitName {
public function methodName() {
// method body
}
}

class MyClass {
use TraitName;
}

Example;

<?php

// First Trait
trait Logger {
public function log($msg) {
echo "Log: $msg\n";
}
}

// Second Trait
trait Printer {
public function print($data) {
echo "Print: $data\n";
}
}

// Class using both traits


class Machine {
use Logger, Printer;

public function start() {


echo "Machine starting...\n";
}
}

// Test
$obj = new Machine();
$obj->start();
$obj->log("System boot successful");
$obj->print("Report.pdf");

?>

Important Notes:

If two traits have methods with the same name, you must resolve conflicts using insteadof
and as keywords.

Traits cannot be instantiated on their own — they are included inside classes.

11. Create a class as “Percentage” with two properties length & width. Calculate area of
rectangle for two objects.

Ans.

<?php

class Percentage {
public $length;
public $width;

// Constructor to initialize properties


public function __construct($length, $width) {
$this->length = $length;
$this->width = $width;
}

// Method to calculate area


public function calculateArea() {
return $this->length * $this->width;
}
}

// Create first object


$rect1 = new Percentage(10, 5);
echo "Area of Rectangle 1: " . $rect1->calculateArea() . "\n";

// Create second object


$rect2 = new Percentage(8, 7);
echo "Area of Rectangle 2: " . $rect2->calculateArea() . "\n";

?>

Chapter 4 (CO 4)

1. Explain GET and POST methods in detail with example.

Ans..

🌐 What are GET and POST Methods?


GET and POST are two HTTP request methods used to send data from a client (like a
browser) to the server.

They are commonly used in HTML forms and URLs.

✅ GET Method

🔹 Features:
Sends data through the URL

Can be bookmarked

Visible to user (less secure)

Limited data length (~2000 characters)


Useful for search forms, filtering, etc.

🔹 Example:

<!-- get_form.html -->


<form method="GET" action="get_example.php">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>

// get_example.php
<?php
$name = $_GET['name'];
echo "Hello, $name!";
?>

✅ POST Method

🔹 Features:
Sends data in the request body (not in the URL)

Cannot be bookmarked

More secure than GET (data not shown in address bar)

No size limitations

Useful for login forms, registration, file uploads, etc.

🔹 Example:

<!-- post_form.html -->


<form method="POST" action="post_example.php">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>

// post_example.php
<?php
$name = $_POST['name'];
echo "Hello, $name!";
?>

2. Differentiate between Session and Cookies.

Ans.

3. Define session and cookie.Explain use of session start.

Ans.

🔐 What is a Session in PHP?

A session is a way to store user data on the server across multiple pages.

Each user gets a unique session ID

Data is stored on the server (secure)

Commonly used for login, shopping cart, etc.


✅ Use of session_start()

session_start() is a PHP function used to start a session or resume an existing one.

It must be called at the beginning of your script before any HTML output.

It makes the $_SESSION superglobal array available for use.

Example:

<?php
session_start(); // Start the session

$_SESSION['username'] = "Alice"; // Set session variable

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


?>

🍪 What is a Cookie in PHP?

A cookie is a small piece of data stored on the client-side (browser).

Used to remember information between visits

Stored as a text file on the user's computer

Can store username, preferences, etc.

4. Answer the following: i) start session ii) Get session variables ii) Destroy session

Ans.

i) Start a Session

To start a session, use the session_start() function.


It should be placed at the top of your PHP file (before any HTML output).

Ex:
<?php
session_start(); // Start or resume a session
?>

ii) Get Session Variables


Once the session is started and values are set using $_SESSION, you can access them like
this:

<?php
session_start(); // Always start session before accessing it

// Set session variable


$_SESSION['username'] = "Alice";

// Get session variable


echo "Username is: " . $_SESSION['username'];
?>

iii) Destroy a Session


To delete all session data and end the session:

<?php
session_start(); // Start the session first
session_unset(); // Remove all session variables
session_destroy(); // Destroy the session
?>

After this, the $_SESSION array is empty, and the session is terminated.

5. Create Employee form like Employee_name, Address, Mobile_no,Date of birth, Post


and Salary using different form input element and display user inserted values in new
PHP form

Ans.

Let's create a simple PHP form to collect Employee details and then display the submitted
values on a separate page.

Step 1: employee_form.html

<!-- employee_form.html -->


<!DOCTYPE html>
<html>
<head>
<title>Employee Form</title>
</head>
<body>
<h2>Employee Registration Form</h2>
<form action="display_employee.php" method="POST">
<label>Employee Name:</label>
<input type="text" name="emp_name" required><br><br>

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

<label>Mobile No:</label>
<input type="tel" name="mobile_no" pattern="[0-9]{10}" required><br><br>

<label>Date of Birth:</label>
<input type="date" name="dob" required><br><br>

<label>Post:</label>
<select name="post" required>
<option value="Manager">Manager</option>
<option value="Developer">Developer</option>
<option value="Designer">Designer</option>
<option value="HR">HR</option>
</select><br><br>

<label>Salary:</label>
<input type="number" name="salary" required><br><br>

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


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

Step 2: display_employee.php

<!-- display_employee.php -->


<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['emp_name'];
$address = $_POST['address'];
$mobile = $_POST['mobile_no'];
$dob = $_POST['dob'];
$post = $_POST['post'];
$salary = $_POST['salary'];

echo "<h2>Employee Details:</h2>";


echo "Name: $name <br>";
echo "Address: $address <br>";
echo "Mobile No: $mobile <br>";
echo "Date of Birth: $dob <br>";
echo "Post: $post <br>";
echo "Salary: ₹$salary <br>";
}
?>

6. Explain web page validation with example.

Ans.

🌐 What is Web Page Validation?


Validation ensures that the data entered by users in a form is correct, complete, and safe
before being processed or stored.

✅ Types of Validation:

Client-side Validation (Done in the browser using HTML5 or JavaScript)

Server-side Validation (Done on the server using PHP or other backend language)

Client-side Validation (HTML5 Example)

This checks data before submission, improving user experience.

<form action="process.php" method="POST">


Name: <input type="text" name="name" required><br><br>

Email: <input type="email" name="email" required><br><br>

Age: <input type="number" name="age" min="18" max="60" required><br><br>

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


</form>

Server-side Validation (PHP Example)

Always use server-side validation for security, as client-side can be bypassed.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST['name']);
$email = $_POST['email'];
$age = $_POST['age'];

// Check for empty name


if (empty($name)) {
echo "Name is required.<br>";
}

// Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.<br>";
}

// Check age range


if ($age < 18 || $age > 60) {
echo "Age must be between 18 and 60.<br>";
}

if (!empty($name) && filter_var($email, FILTER_VALIDATE_EMAIL) && $age


>= 18 && $age <= 60) {
echo "Form submitted successfully!";
}
}
?>

7. State the use of Cookies.

Ans.

✅ What is a Cookie?
A cookie is a small piece of data that a server stores on the user's browser to remember
information across different pages or visits.

Uses of Cookies:
Important Notes:

Cookies are stored in the browser.

Maximum size: ~4KB per cookie.

They can be seen and edited by users, so never store sensitive info in cookies.

Use HTTPS and secure flags for secure cookies.

8. Explain how to create ,Modify and delete/destroy cookies in PHP

Ans.

1. Create a Cookie
Use the setcookie() function:

<?php
// Syntax: setcookie(name, value, expire_time)
setcookie("username", "Alice", time() + 3600); // Expires in 1 hour
echo "Cookie has been set.";
?>

2. Modify (Update) a Cookie


To modify a cookie, just set it again with the same name and a new value:

<?php
// Update the existing cookie
setcookie("username", "Bob", time() + 3600); // New value is Bob
echo "Cookie has been updated.";
?>

3. Delete (Destroy) a Cookie


To delete a cookie, set its expiration time in the past:

<?php
// Delete the cookie by setting its expiry in the past
setcookie("username", "", time() - 3600);
echo "Cookie has been deleted.";
?>

🔍 To Access a Cookie
Use the $_COOKIE superglobal array:

<?php
if (isset($_COOKIE['username'])) {
echo "Welcome, " . $_COOKIE['username'];
} else {
echo "No cookie found.";
}
?>

9. Explain mail() function in PHP with example.

Ans.

📧 mail() Function in PHP:

The mail() function is used to send emails directly from a PHP script.

✅ Syntax:

mail(to, subject, message, headers, parameters);


📌 Basic Example:

<?php
$to = "[email protected]"; // Receiver
$subject = "Welcome to My Website"; // Subject
$message = "Hello! Thank you for signing up."; // Message body
$headers = "From: [email protected]"; // Header

if(mail($to, $subject, $message, $headers)) {


echo "Email sent successfully!";
} else {
echo "Failed to send email.";
}
?>

Important Notes:

It won't work out-of-the-box on localhost unless properly configured.

For reliable sending, especially with Gmail or external services, use libraries like
PHPMailer or SMTP authentication.


Chapter 5 (CO 5)
1. Write syntax of Connecting PHP Webpage with MySQL

Ans.

Here's the syntax to connect a PHP webpage with a MySQL database using mysqli:

<?php
$servername = "localhost"; // usually "localhost"
$username = "root"; // default for local server
$password = ""; // default is empty in XAMPP
$dbname = "your_database"; // name of your database

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>

2. List out the database operations.

Ans.

3. Write Update and Delete operations on table data


Ans.

1. Create Table and Insert Record

<?php
// Create connection
$conn = mysqli_connect("localhost", "root", "", "test_db");

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Create table
$createTable = "CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
salary INT
)";
mysqli_query($conn, $createTable);

// Insert record
$insertData = "INSERT INTO employees (name, email, salary)
VALUES ('Alice Smith', '[email protected]', 45000)";
if (mysqli_query($conn, $insertData)) {
echo "Record inserted successfully!";
} else {
echo "Error inserting record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

2. Update Record

<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Update salary of employee with id = 1
$update = "UPDATE employees SET salary = 50000 WHERE id = 1";

if (mysqli_query($conn, $update)) {
echo "Record updated successfully!";
} else {
echo "Error updating record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

3. Delete Record

<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Delete employee with id = 1


$delete = "DELETE FROM employees WHERE id = 1";

if (mysqli_query($conn, $delete)) {
echo "Record deleted successfully!";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

4. Explain Inserting and Retrieving the query result operations

Ans.

1. Inserting Data into Database


To insert data into a table, use the INSERT INTO SQL command with PHP’s
mysqli_query().

✅ Example: Insert Data


<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");

$sql = "CREATE TABLE IF NOT EXISTS employees (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
salary INT
)";

mysqli_query($conn, $sql);

$sql_in = "INSERT INTO employees (name, email, salary)


VALUES ('Alice', '[email protected]', 50000)";

if (mysqli_query($conn, $sql_in)) {
echo "Data inserted successfully!";
} else {
echo "Error: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

2. Retrieving (Fetching) Data from Database


To get data from the database, use the SELECT statement and fetch results using
functions like:

mysqli_fetch_assoc() – returns associative array (recommended)

mysqli_fetch_row() – returns numeric array

✅ Example: Retrieve and Display Data

<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");

$sql = "SELECT * FROM employees";


$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// Output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . "<br>";
echo "Name: " . $row["name"] . "<br>";
echo "Email: " . $row["email"] . "<br>";
echo "Salary: " . $row["salary"] . "<br><hr>";
}
} else {
echo "No records found!";
}

mysqli_close($conn);
?>

5. Write a program to connect PHP with MySQL

Ans.

Here's a simple PHP program to connect PHP with MySQL using the mysqli extension.

<?php
// Step 1: Set connection variables
$servername = "localhost"; // usually localhost
$username = "root"; // default for XAMPP
$password = ""; // default password is blank
$dbname = "test_db"; // name of your database

// Step 2: Create connection


$conn = mysqli_connect($servername, $username, $password, $dbname);

// Step 3: Check connection


if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

echo "Connected to MySQL database successfully!";

// Step 4: Close connection


mysqli_close($conn);
?>

6. Elaborate the following: ii) mysqli_connect()

Ans,
✅ Definition:
The mysqli_connect() function is used to establish a connection between a PHP script and
a MySQL database.

Syntax:

mysqli_connect(hostname, username, password, database);

Parameter Description

hostname Usually "localhost" for local server

username MySQL username (default is "root" in XAMPP)

password MySQL password (default is "" empty)

database Name of the database to connect to

✅ Example:

<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>

7. List any four data types in MySQL.

Ans.

1. INT

Used to store whole numbers (integers).

Example: 1, 250, -10

Ex:
age INT;

2. VARCHAR(n)

Used to store variable-length strings (text).

n defines the maximum number of characters.

Example: names, emails, etc.

Ex:
name VARCHAR(100);

3. DATE

Used to store dates in YYYY-MM-DD format.

Example: 2025-04-05

Ex:
dob DATE;

4. FLOAT / DOUBLE

Used to store decimal numbers.

Example: prices, percentages

Ex:
price FLOAT;

You might also like