Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

KTU Web Programming QPs

The document outlines steps for establishing a PHP-MySQL connection, including creating a database, connecting using mysqli, and closing the connection. It also provides examples of PHP loops, functions, and basic operations with associative arrays, as well as a PHP program for user authentication and cookie management. Additionally, it explains the dynamic typing nature of PHP and the differences between implode and explode functions.

Uploaded by

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

KTU Web Programming QPs

The document outlines steps for establishing a PHP-MySQL connection, including creating a database, connecting using mysqli, and closing the connection. It also provides examples of PHP loops, functions, and basic operations with associative arrays, as well as a PHP program for user authentication and cookie management. Additionally, it explains the dynamic typing nature of PHP and the differences between implode and explode functions.

Uploaded by

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

1) Discuss the various steps for establishing a PHP-My SQL connection

with a MY SQL database.


Ans)
To establish a PHP-MySQL connection with a MySQL database, follow these simple steps:

1. Create Database in MySQL:

Use MySQL or phpMyAdmin to create your database:


CREATE DATABASE your_database_name;


2. Connect PHP to MySQL:

In your PHP file, use the following code:


$conn = new mysqli("localhost", "username", "password", "your_database_name");

// 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();

2) Illustrate with a sample script how CREATE operations in MY SQL are


implemented in PHP.
Ans)

PHP script that demonstrates how CREATE operations (e.g., creating a table) are implemented
in MySQL using PHP:

PHP Script for CREATE Operation:


<?php
// Step 1: Establish MySQL Connection
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "your_database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Step 2: SQL Query to Create Table


$sql = "CREATE TABLE Students (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";

// Step 3: Execute the Query


if ($conn->query($sql) === TRUE) {
echo "Table 'Students' created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

// Step 4: Close the connection


$conn->close();
?>
3)a) Explain loops in PHP with examples.

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:

The number is: 1


The number is: 2
The number is: 3
The number is: 4
The number is: 5

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:

The number is: 1


The number is: 2
The number is: 3
The number is: 4
The number is: 5

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:

for (initialization; condition; increment) {


// Code to be executed
}

Example:

<?php
for ($i = 1; $i <= 5; $i++) {
echo "The number is: $i<br>";
}
?>

Output:

The number is: 1


The number is: 2
The number is: 3
The number is: 4
The number is: 5

4. foreach Loop

The foreach loop is specifically used for iterating over arrays. It loops through each key/value
pair in an array.

Syntax:

foreach ($array as $value) {


// Code to be executed
}
foreach ($array as $key => $value) {
// Code to be executed
}

Example:

<?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo "The color is: $color<br>";
}
?>

Output:

The color is: red


The color is: green
The color is: blue

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

b) Write equivalent PHP statement corresponding to the following:

i) Declare an associative array named "ages" to store the key-value pairs


("Harry",21),("Alice",20),("Megha",22),("Bob",19).

Ans)
To declare an associative array named "ages" in PHP with the key-value pairs:

● "Harry" => 21
● "Alice" => 20
● "Megha" => 22
● "Bob" => 19

The equivalent PHP statement is:

$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;

This will update the value of "Megha" to 28 in the $ages array

iii) Sort the array according to values maintaining the key-value


relationships and print the sorted key-value pairs.

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);

// Sort the array by values while maintaining key-value pairs


asort($ages);
// Print the sorted key-value pairs
foreach ($ages as $key => $value) {
echo $key . " : " . $value . "\n";
}
?>

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

iv)The entry identified by the key "Alice".

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);

// Sort the array by values while maintaining key-value pairs


asort($ages);

// Print the entry identified by the key "Alice"


if (array_key_exists("Alice", $ages)) {
echo "Alice : " . $ages["Alice"] . "\n";
} else {
echo "Key 'Alice' does not exist in the array.\n";
}
?>

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

4) a) Illustrate with a sample PHP script how functions are implemented in


PHP.
Ans)
PHP script that demonstrates how functions are implemented in PHP. The example will show
how to define a simple function, pass parameters to it, and return a value.

Sample PHP Script:


<?php
// Function to add two numbers
function addNumbers($a, $b) {
// Return the sum of two numbers
return $a + $b;
}

// Function to greet a user


function greetUser($name) {
// Return a greeting message
return "Hello, " . $name . "!";
}

// Function to calculate the factorial of a number


function factorial($n) {
// Initialize the result to 1
$result = 1;

// Use a loop to calculate factorial


for ($i = 1; $i <= $n; $i++) {
$result *= $i;
}

// Return the factorial result


return $result;
}

// Calling the functions and displaying the results

// Adding two numbers


echo "Sum of 5 and 3 is: " . addNumbers(5, 3) . "\n";

// Greeting a user
echo greetUser("Alice") . "\n";

// Calculating the factorial of 5


echo "Factorial of 5 is: " . factorial(5) . "\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.

b) Why is PHP considered to be dynamically typed? Distinguish b/w


implode and explode function in PHP with suitable examples.

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

$var = 10; // Initially an integer

echo gettype($var); // Outputs: integer

$var = "Hello, World!"; // Now a string

echo gettype($var); // Outputs: string

In this example, the variable $var changes its type from integer to string without any explicit type
declaration.

Difference Between implode and explode

explode

The explode() function splits a string into an array based on a specified delimiter.

Syntax:

array explode(string $delimiter, string $string, int $limit = PHP_INT_MAX)

● $delimiter: The boundary string at which the string will be split.


● $string: The input string to be split.
● $limit (optional): If specified, it will limit the number of elements in the resulting array.

Example:

$string = "apple,banana,orange";

$array = explode(",", $string);

print_r($array);

Output:

Array

(
[0] => apple

[1] => banana

[2] => orange

implode

The implode() function joins array elements into a single string using a specified delimiter.

Syntax

string implode(string $glue, array $pieces)

● $glue: The string to be used as a separator between the elements.


● $pieces: The array of strings to join together.

Example:

$array = array("apple", "banana", "orange");

$string = implode(",", $array);

echo $string;

Output:

Apple,banana,orange

5) Write a php program to compute the sum of the positive integers up to


100 using do while.

Ans)

PHP program that computes the sum of positive integers up to 100 using a do...while loop:

<?php

$sum = 0; // Initialize the sum variable

$i = 1; // Initialize the counter variable


do {

$sum += $i; // Add the current value of $i to the sum

$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.

When you run this program, it will output:

The sum of positive integers up to 100 is: 5050

6) Write a PHP form handling program to verify the user authentication


credentials of a web page using MYSQL connection and store the userid
value as a session variable if the userid is valid.

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.

PHP Form Handling Program

1. Database Setup: Make sure you have a users table in your MySQL database:
CREATE TABLE users (

user_id VARCHAR(50) NOT NULL,

password VARCHAR(255) NOT NULL,

PRIMARY KEY (user_id)

);

-- Insert a sample user (password should be hashed in a real application)

INSERT INTO users (user_id, password) VALUES ('testuser', 'password123');

2. PHP Code:

<?php

session_start(); // Start the session

// Database connection

$conn = new mysqli("localhost", "root", "", "your_database"); // Update with your details

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

// Handle form submission

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$user_id = $_POST['user_id'];

$password = $_POST['password'];

// Prepare and execute the SQL statement

$stmt = $conn->prepare("SELECT * FROM users WHERE user_id = ? AND password = ?");


$stmt->bind_param("ss", $user_id, $password); // Use password_hash() in practice

$stmt->execute();

$result = $stmt->get_result();

// Check for valid user

if ($result->num_rows > 0) {

$_SESSION['user_id'] = $user_id; // Store user_id in session

echo "Login successful! Welcome, " . htmlspecialchars($user_id);

} else {

echo "Invalid user ID or password.";

$stmt->close();

$conn->close();

?>

<!DOCTYPE html>

<html>

<head>

<title>User Authentication</title>

</head>

<body>
<h2>Login Form</h2>

<form method="post" action="">

User ID:<br>

<input type="text" name="user_id" required><br>

Password:<br>

<input type="password" name="password" required><br><br>

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

</form>

</body>

</html>

Key Components Explained:

1. Session Management: session_start() initiates a session to store user data.


2. Database Connection: Connects to the MySQL database. Adjust the connection
parameters as needed.
3. Form Handling: The script processes data when the form is submitted. It retrieves the
user_id and password.
4. Prepared Statements: A prepared statement prevents SQL injection attacks by safely
binding parameters.
5. User Verification: If the user is authenticated, their ID is stored in the session. If
authentication fails, an error message is displayed.
6. HTML Form: A simple form collects user credentials.

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)

Uses of Cookies in Web Pages

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.

Syntax for Setting Cookies in PHP

You can set cookies in PHP using the setcookie() function. Here’s the syntax:

setcookie(name, value, expire, path, domain, secure, httponly);

Parameters:

● name: The name of the cookie.


● value: The value associated with the cookie.
● expire: The expiration time of the cookie (Unix timestamp). If not set, the cookie lasts
until the session ends.
● path: The server path where the cookie is available. Use '/' for the entire domain.
● domain: The domain for which the cookie is valid.
● secure: If true, the cookie is only sent over HTTPS.
● httponly: If true, the cookie is inaccessible via JavaScript.

Example:

setcookie("username", "JohnDoe", time() + (86400 * 30), "/"); // Expires in 30 days

Accessing Cookies in PHP

To access a cookie, use the $_COOKIE superglobal array:

if (isset($_COOKIE['username'])) {

echo "Hello, " . $_COOKIE['username']; // Outputs: Hello, JohnDoe

} else {
echo "Cookie is not set.";

Deleting Cookies in PHP

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

setcookie("username", "", time() - 3600, "/"); // Deletes the cookie

Example of Setting, Accessing, and Deleting a Cookie

<?php

// Setting a cookie

setcookie("username", "JohnDoe", time() + (86400 * 30), "/");

// Accessing the cookie

if (isset($_COOKIE['username'])) {

echo "Hello, " . $_COOKIE['username']; // Outputs: Hello, JohnDoe

} else {

echo "Cookie is not set.";

// Deleting the cookie

setcookie("username", "", time() - 3600, "/"); // Set expiration to the past

?>

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().

8) Write a php form handling program to perform the user registration of


any website with a minimum of 5 different fields and insert the data into a
MYSQL table after establishing necessary connections with the DB.

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:

CREATE TABLE users (

id INT(11) AUTO_INCREMENT PRIMARY KEY,

username VARCHAR(50) NOT NULL,

email VARCHAR(100) NOT NULL,

password VARCHAR(255) NOT NULL,

age INT(3),

gender ENUM('Male', 'Female', 'Other') NOT NULL

);

2. PHP User Registration Program

Here’s a complete PHP script for user registration:

<?php

// Start session

session_start();
// Database connection parameters

$servername = "localhost"; // Change if your server is different

$username = "root"; // Your MySQL username

$password = ""; // Your MySQL password

$dbname = "your_database"; // Your database name

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

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

// Handle form submission

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$username = $_POST['username'];

$email = $_POST['email'];

$password = password_hash($_POST['password'], PASSWORD_DEFAULT); // Hash the


password

$age = $_POST['age'];

$gender = $_POST['gender'];

// Prepare and bind


$stmt = $conn->prepare("INSERT INTO users (username, email, password, age, gender)
VALUES (?, ?, ?, ?, ?)");

$stmt->bind_param("sssis", $username, $email, $password, $age, $gender);

// Execute the statement

if ($stmt->execute()) {

echo "Registration successful!";

} else {

echo "Error: " . $stmt->error;

// Close the statement

$stmt->close();

// Close the connection

$conn->close();

?>

<!DOCTYPE html>

<html>

<head>

<title>User Registration</title>

</head>

<body>
<h2>Registration Form</h2>

<form method="post" action="">

Username:<br>

<input type="text" name="username" required><br>

Email:<br>

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

Password:<br>

<input type="password" name="password" required><br>

Age:<br>

<input type="number" name="age" required><br>

Gender:<br>

<select name="gender" required>

<option value="Male">Male</option>

<option value="Female">Female</option>

<option value="Other">Other</option>

</select><br><br>

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

</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.

You might also like