KTU Web Programming QPs
KTU Web Programming QPs
○
2. Connect PHP to MySQL:
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
○
3. Close the Connection:
○ After executing your operations, close the connection:
$conn->close();
PHP script that demonstrates how CREATE operations (e.g., creating a table) are implemented
in MySQL using PHP:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Ans)
In PHP, loops are used to execute a block of code repeatedly as long as a specified condition
is true. PHP supports several types of loops:
1. while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax:
while (condition) {
// Code to be executed
}
Example:
<?php
$i = 1;
while ($i <= 5) {
echo "The number is: $i<br>";
$i++;
}
?>
Output:
2. do...while Loop
The do...while loop will execute the code block once, before checking if the condition is true. It
will then repeat the loop as long as the condition is true.
Syntax:
do {
// Code to be executed
} while (condition);
Example:
<?php
$i = 1;
do {
echo "The number is: $i<br>";
$i++;
} while ($i <= 5);
?>
Output:
Note: Even if $i was greater than 5, this loop would still run at least once.
3. for Loop
The for loop is the most compact form of looping. It is typically used when the number of
iterations is known beforehand.
Syntax:
Example:
<?php
for ($i = 1; $i <= 5; $i++) {
echo "The number is: $i<br>";
}
?>
Output:
4. foreach Loop
The foreach loop is specifically used for iterating over arrays. It loops through each key/value
pair in an array.
Syntax:
Example:
<?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo "The color is: $color<br>";
}
?>
Output:
You can also use foreach to access both keys and values:
<?php
$person = array("name" => "John", "age" => 30, "city" => "New York");
foreach ($person as $key => $value) {
echo "$key: $value<br>";
}
?>
Output:
name: John
age: 30
city: New York
Ans)
To declare an associative array named "ages" in PHP with the key-value pairs:
● "Harry" => 21
● "Alice" => 20
● "Megha" => 22
● "Bob" => 19
$ages = array(
"Harry" => 21,
"Alice" => 20,
"Megha" => 22,
"Bob" => 19
);
This creates an associative array where the names are the keys, and their corresponding ages
are the values.
ii) Modify the value associated with the key "Megha" to 28.
Ans) To modify the value associated with the key "Megha" to 28 in the associative array, you
can do this in PHP by directly assigning the new value to the key like so:
$ages["Megha"] = 28;
Ans)
To sort the associative array by values while maintaining the key-value relationships, you can
use the asort() function in PHP. Here's how to do it, along with printing the sorted key-value
pairs:
<?php
// Associative array
$ages = array("Harry" => 21, "Alice" => 20, "Megha" => 28, "Bob" => 19);
Explanation:
● asort() sorts the array by values in ascending order, maintaining the key-value
association.
● The foreach loop is used to print each key-value pair after sorting.
Output:
Bob : 19
Alice : 20
Harry : 21
Megha : 28
Ans)If you want to specifically print the entry identified by the key "Alice", you can access it
directly from the associative array. Here's the modified code to print just the key-value pair for
"Alice":
<?php
// Associative array
$ages = array("Harry" => 21, "Alice" => 20, "Megha" => 28, "Bob" => 19);
Explanation:
● array_key_exists("Alice", $ages) checks if the key "Alice" exists in the array.
● If the key exists, the value associated with "Alice" is printed.
Output:
Alice : 20
// Greeting a user
echo greetUser("Alice") . "\n";
?>
Explanation:
1. addNumbers($a, $b):
○ A function that takes two parameters ($a and $b) and returns their sum.
2. greetUser($name):
○ This function takes a string parameter $name and returns a greeting message
with that name.
3. factorial($n):
○ The function calculates the factorial of a given number $n using a for loop and
returns the result.
4. Calling the Functions:
○ The functions are called with appropriate arguments, and the results are
displayed using echo.
Output:
Sum of 5 and 3 is: 8
Hello, Alice!
Factorial of 5 is: 120
This example covers how to define and use functions in PHP, pass parameters, perform
operations inside the functions, and return results.
Ans)
PHP is considered a dynamically typed language because variable types are determined at
runtime rather than at compile time. This means you don't have to declare a variable's data type
explicitly; PHP will automatically convert the variable to the appropriate type based on the
context in which it is used.
Example of Dynamic Typing in PHP
In this example, the variable $var changes its type from integer to string without any explicit type
declaration.
explode
The explode() function splits a string into an array based on a specified delimiter.
Syntax:
Example:
$string = "apple,banana,orange";
print_r($array);
Output:
Array
(
[0] => apple
implode
The implode() function joins array elements into a single string using a specified delimiter.
Syntax
Example:
echo $string;
Output:
Apple,banana,orange
Ans)
PHP program that computes the sum of positive integers up to 100 using a do...while loop:
<?php
$i++; // Increment $i by 1
} while ($i <= 100); // Continue the loop while $i is less than or equal to 100
echo "The sum of positive integers up to 100 is: $sum"; // Output the result
?>
Explanation:
● We initialize a variable $sum to hold the cumulative sum and a counter variable $i
starting at 1.
● The do...while loop will execute the block of code at least once, adding the value of $i to
$sum and then incrementing $i.
● The loop continues until $i exceeds 100.
● Finally, we print the total sum.
Ans)
PHP form handling program that verifies user authentication credentials using MySQL, suitable
for an 8-mark question. This version includes essential elements while ensuring clarity and
brevity.
1. Database Setup: Make sure you have a users table in your MySQL database:
CREATE TABLE users (
);
2. PHP Code:
<?php
// Database connection
$conn = new mysqli("localhost", "root", "", "your_database"); // Update with your details
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user_id = $_POST['user_id'];
$password = $_POST['password'];
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
} else {
$stmt->close();
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>User Authentication</title>
</head>
<body>
<h2>Login Form</h2>
User ID:<br>
Password:<br>
</form>
</body>
</html>
7) What are the uses of cookies in web pages? Describe syntax for setting
cookies in PHP.How can you access and delete the cookies using
setcookie().
Ans)
Cookies are small pieces of data stored on the client-side by the web browser. They serve
several important purposes:
1. User Authentication: Cookies store session information, allowing users to remain
logged in as they navigate through the site.
2. User Preferences: They remember user preferences (e.g., language, theme) to
enhance the user experience during future visits.
3. Tracking and Analytics: Cookies track user behavior, helping website owners analyze
traffic and improve site performance.
4. Shopping Carts: E-commerce sites use cookies to remember items in a user’s
shopping cart, even when they leave the site.
5. Ad Targeting: Cookies are utilized to deliver personalized advertisements based on
user behavior and preferences.
You can set cookies in PHP using the setcookie() function. Here’s the syntax:
Parameters:
Example:
if (isset($_COOKIE['username'])) {
} else {
echo "Cookie is not set.";
<?php
// Setting a cookie
if (isset($_COOKIE['username'])) {
} else {
?>
Summary
● Uses: User authentication, preferences, tracking, shopping carts, and ad targeting.
● Setting Cookies: Use setcookie() with appropriate parameters.
● Accessing Cookies: Access using the $_COOKIE array.
● Deleting Cookies: Set the expiration date to the past with setcookie().
Ans)PHP program for user registration that includes five fields and inserts the data into a
MySQL database. This example will cover the necessary steps to establish a database
connection, create a registration form, handle form submissions, and insert the data into a
database table.
1. Database Setup
First, create a MySQL table to store user registration information. Run the following SQL queries
in your MySQL database:
age INT(3),
);
<?php
// Start session
session_start();
// Database connection parameters
// Create connection
// Check connection
if ($conn->connect_error) {
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$email = $_POST['email'];
$age = $_POST['age'];
$gender = $_POST['gender'];
if ($stmt->execute()) {
} else {
$stmt->close();
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h2>Registration Form</h2>
Username:<br>
Email:<br>
Password:<br>
Age:<br>
Gender:<br>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select><br><br>
</form>
</body>
</html>
Explanation
1. Database Connection: The script establishes a connection to the MySQL database
using mysqli.
2. Form Submission Handling:
○ The script checks if the request method is POST.
○ It retrieves data from the form fields: username, email, password, age, and
gender.
○ The password is hashed using password_hash() for security.
3. Prepared Statement:
○ A prepared statement is created to safely insert user data into the users table.
○ The bind_param() method binds the parameters to the SQL query.
4. Execute the Statement: The prepared statement is executed. If successful, a
confirmation message is displayed.
5. HTML Form: The HTML form collects user registration data and submits it to the same
PHP script.