OST Lab Mannual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

1.

SIMPLE WEBPAGE USING PHP

HOME PAGE

<html>
<head>
<title>Login page</title>
</head>
<body>
<br><br>
<h1 style="font-family:Comic Sans Ms;font-size:20pt;text-align:center;color:Blue;">Simple
Message Passsing Site</h1>
<br><hr><br>
<form name="login" method="post" action="msg1.php">
<table align="center" cellpadding="5" cellspacing="5">
<tr>
<td>Enter your name</td>
<td><input type="text" name="t1"/></td>
<tr>
<tr>
<td>Type your message</td>
<td><textarea name="t2"></textarea></td>
</tr>
<tr>
<td><input type="submit" value="Login"/></td>
<td align="center"><input type="reset" value="Cancel"/></td>
</tr>
</table>
</form>
</body>
</html>
MESSAGE PAGE

<?php
$a=$_POST["t1"];$b=$_POST["t2"];
?>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<br><br>
<div>
<label style="color:Green">Hello All!!!</label><?php echo "<h1
style='color:Red;'>$a</h1>";?>
<br>
<br>
<label style="color:Green">Your Message is :</label><?php echo "<h1
style='color:Red;'>$b</h1>";?>
</div>
</table>
</body>
</html>
OUTPUT
2. CONDITIONAL STATEMENTS – FINDING NUMBER SIGN

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Conditional Statements in PHP</title>
<style>
body
{
font-family: Arial, sans-serif;
margin: 20px;
}
h2
{
color: #2c3e50;
}
.result
{
font-weight: bold;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Check Number Sign</h1>
<form method="POST">
<label for="number">Enter a number:</label>
<input type="number" id="number" name="number" required>
<button type="submit">Check</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$number = $_POST['number'];
// Conditional statements to check if the number is positive, negative, or zero
if ($number > 0)
{
$result = "$number is a positive number.";
} elseif ($number < 0)
{
$result = "$number is a negative number.";
} else {
$result = "The number is zero.";
}
// Display the result
echo "<div class='result'>$result</div>";
}
?>
</body>
</html>
OUTPUT
SWITCH CASE

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Day of the Week</title>
</head>
<body>
<h1>Find the Day of the Week</h1>
<form method="post">
<label for="dayNumber">Enter a number (1-7):</label>
<input type="number" name="dayNumber" min="1" max="7" required>
<br>
<input type="submit" value="Get Day">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$dayNumber = intval($_POST['dayNumber']);
// Determine the day of the week
switch ($dayNumber) {
case 1:
$day = "Monday";
break;
case 2:
$day = "Tuesday";
break;
case 3:
$day = "Wednesday";
break;
case 4:
$day = "Thursday";
break;
case 5:
$day = "Friday";
break;
case 6:
$day = "Saturday";
break;
case 7:
$day = "Sunday";
break;
default:
$day = "Invalid input. Please enter a number between 1 and 7.";
}
// Display the result
echo "<h2>Result:</h2>";
echo "The day is: $day";
}
?>
</body>
</html>
OUTPUT
FOR EACH LOOP

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fruits List</title>
</head>
<body>
<h1>Enter Fruits</h1>
<form method="post">
<label for="fruits">Enter fruits (comma separated):</label>
<input type="text" name="fruits" required>
<br>
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// Retrieve and sanitize user input
$fruitsInput = $_POST['fruits'];
// Convert the input string into an array
$fruits = explode(',', $fruitsInput);
// Trim whitespace and remove empty values
$fruits = array_map('trim', array_filter($fruits));
// Display the list of fruits using foreach loop
echo "<h2>List of Fruits:</h2>";
echo "<ul>";
foreach ($fruits as $fruit)
{
echo "<li>$fruit</li>";
}
echo "</ul>";
}
?>
</body>
</html>
OUTPUT
FOR LOOP

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic For Loop Example</title>
</head>
<body>
<h1>Dynamic For Loop Input</h1>
<form method="post">
<label for="start">Start Value:</label>
<input type="number" name="start" required>
<br>
<label for="end">End Value:</label>
<input type="number" name="end" required> <br>
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$start = intval($_POST['start']);
$end = intval($_POST['end']);
echo "<h2>Dynamic For Loop Results:</h2>";
// For loop to iterate from start to end
for ($i = $start; $i <= $end; $i++) {
echo "Number: $i <br>";
}
}
?>
</body>
</html>
OUTPUT
DO WHILE LOOP

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Do While Loop</title>
</head>
<body>
<h1>Display Message</h1>
<form method="post">
<label for="count">Enter a number:</label>
<input type="number" name="count" required>
<br>
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve user input
$count = intval($_POST['count']);
$i = 0;
do {
echo "WELCOME TO III BCA !<br>";
$i++;
} while ($i < $count);
}
?>
</body>
</html>
OUTPUT
3. DIFFERENT TYPES OF ARRAYS

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Types of Arrays in PHP</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h2 {
color: #2c3e50;
}
pre {
background-color: #f9f9f9;
padding: 10px;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<h1>Different Types of Arrays in PHP</h1>

<?php
// 1. Indexed Array
$fruits = ["Apple", "Banana", "Cherry"];
echo "<h2>Indexed Array</h2>";
echo "<pre>";
print_r($fruits);
echo "</pre>";

// 2. Associative Array
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
echo "<h2>Associative Array</h2>";
echo "<pre>";
print_r($person);
echo "</pre>";

// 3. Multidimensional Array
$contacts = [
["name" => "John", "email" => "[email protected]"],
["name" => "Jane", "email" => "[email protected]"]
];
echo "<h2>Multidimensional Array</h2>";
echo "<pre>";
print_r($contacts);
echo "</pre>";
?>
</body>
</html>
OUTPUT
4. USER DEFINED FUNCTION – FIBONACCI SERIES

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fibonacci Series Generator</title>
</head>
<body>
<h1>Fibonacci Series Generator</h1>
<form method="POST">
<label for="number">Enter the number of terms:</label>
<input type="number" id="number" name="number" min="1" required>
<button type="submit">Generate</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$n = intval($_POST['number']);
$fibonacciSeries = generateFibonacci($n);
echo "<h2>Fibonacci Series (first $n terms):</h2>";
echo "<p>" . implode(", ", $fibonacciSeries) . "</p>";
}
function generateFibonacci($n)
{
$fibonacci = [];
// Starting values
$a = 0;
$b = 1;
for ($i = 0; $i < $n; $i++)
{
$fibonacci[] = $a;
// Calculate the next term
$next = $a + $b;
$a = $b;
$b = $next;
}
return $fibonacci;
}
?>
</body>
</html>
OUTPUT
4. USER DEFINED FUNCTION – PALINDROME CHECKER

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Palindrome Checker</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
form {
margin-bottom: 20px;
}
input[type="text"] {
padding: 5px;
width: 200px;
}
button {
padding: 5px 10px;
}
p{
font-weight: bold;
}
</style>
</head>
<body>
<h1>Palindrome Checker</h1>
<form method="POST">
<label for="inputString">Enter a string:</label>
<input type="text" id="inputString" name="inputString" required>
<button type="submit">Check</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
function isPalindrome($string) {
// Remove non-alphanumeric characters and convert to lowercase
$cleanedString = preg_replace("/[^A-Za-z0-9]/", "", $string);
$cleanedString = strtolower($cleanedString);

// Check if the cleaned string is the same forwards and backwards


return $cleanedString === strrev($cleanedString);
}
// Get the input string from the form
$input = $_POST['inputString'];
if (isPalindrome($input)) {
echo "<p>'$input' is a palindrome.</p>";
} else {
echo "<p>'$input' is not a palindrome.</p>";
}
}
?>
</body>
</html>
OUTPUT
5. FILE MANIPULATION USING PHP

READING A FILE

<html>
<head>
<title>reading a file using php</title>
</head>
<body>
<?php
$filename="temp.txt";
$file=fopen($filename,"r");
if($file==false){
echo("error in opening file");
exit();
}
$filesize=filesize($filename);
$filetext=fread($file,$filesize);
fclose($file);
echo("file size:$filesize bytes");
echo("<pre> $filetext</pre>");
?>
</body>
</html>

WRITING TO A FILE

<?php
$filename = "newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false ) {
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>
<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>
<?php
$filename = "newfile.txt";
$file = fopen( $filename, "r" );
if( $file == false ) {
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "$filetext" );
echo("file name: $filename");
?>
</body>
</html>
OUTPUT

READING FROM A FILE

WRITING TO THE FILE


6. CREATION OF SESSIONS
<?php
session_start();
date_default_timezone_set('Asia/Kolkata');
$_SESSION['datetime'] = date('Y-m-d h:i:sa');

// Display the date and time


echo "<b> The current session date and time is: </b>" . $_SESSION['datetime'];
echo "<br>";
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 1;
} else {
$_SESSION['count']++;
}
echo "You have visited this page " . $_SESSION['count'] . " times.";
?>
<html>
<head>
<title>PHP Session Example</title>
</head>
<body>
<FORM method="POST">
Enter Name:<input type="text" name="name"><br>
</br>
<input type="submit" name="submit1" value="session">
<input type="submit" name="submit2" vaLue="view session">
<input type="submit" name="submit3" value="Destroy session">
</FORM>
<?php
if(isset($_POST['submit1']))
{
$_SESSION["sname"]=$_POST["name"];
}
if(isset($_POST['submit2']))
{
if(isset($_SESSION["sname"]))
{
echo "The session value=".$_SESSION["sname"];
}
else
{
echo "All Sessions Destroyed!!";
}
}
if(isset($_POST['submit3']))
{
session_destroy();
}
?>
</body>
</html>
OUTPUT

CREATING A SESSION

VIEWING A SESSION

DESTROYING A SESSION
CREATION OF COOKIES
<html>
<head>
<title>PHP Cookies Example</title>
</head>
<body>
<FORM method="POST" action="firstexample.php">
Enter Name : <input type="text" name="name"><br/>
Enter Age : <input type="text" name="age"><br/>
Enter City : <input type="text" name="city"><br/>
<br/>
<input type="submit" name="Submit1" value="Create Cookie">
<input type="submit" name="Submit2" value="Retrive Cookie">
<input type="submit" name="Submit3" value="Delete Cookie">
</FORM>
<?php
if(isset($_POST["Submit1"]))
{
setcookie("name",$_POST["name"], time() + 3600, "/", "", 0);
setcookie("age", $_POST["age"], time() + 3600, "/", "", 0);
setcookie("city", $_POST["city"], time() + 3600, "/", "", 0);
echo "Cookies Created !!";
}
if(isset($_POST["Submit3"]))
{
setcookie("name","", time() - 3600, "/", "", 0);
setcookie("age", "", time() - 3600, "/", "", 0);
setcookie("city", "", time() - 3600, "/", "", 0);
}
if(isset($_POST['Submit2']))
{
if(isset($_COOKIE["name"]))
{
echo "Name = ".$_COOKIE["name"]."<br/>";
echo "Age = ".$_COOKIE["age"]."<br/>";
echo "City = ".$_COOKIE["city"]."<br/>";
}
else
{
echo "Cookies deleted !!";
}
}
?>
</body>
</html>
OUTPUT

CREATING A COOKIE

RETRIEVING A COOKIE

DELETING A COOKIE
1. TABLE WITH CONSTRAINTS
//Database name: samp
//Table name: users123
//Field name: id int(3) , imageidlongblob
//display-new.php
<!DOCTYPE html>
<html>
<head>
<title>Display Image</title>
<style>body {
background-color: lightpink;
}
table { width: 50%; margin: auto;
border-collapse: collapse;
}
th, td {
border: 1px solid black;padding: 8px;
text-align: center;
}
</style>
</head>
<body>
<center>
<h1>VOTE FOR ME</h1>
<form action="" method="post" enctype="multipart/form-data">
<table>
<thead>
<tr>
<th>Id</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<?php
// Database connection
$connection = mysqli_connect("localhost", "root", "", "samp");
// Check connectionif (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Query to fetch all records from users123
$query = "SELECT * FROM users123";
$query_run = mysqli_query($connection, $query);
// Fetch and display each record while ($row = mysqli_fetch_assoc($query_run)) {
$imageData = base64_encode($row['imageid']);
$mimeType = 'image/jpeg'; // Adjust this if your images are of a different type
?>
<tr>
<td><?php echo htmlspecialchars($row['id']); ?></td>
<td>
<imgsrc="data:<?php echo $mimeType; ?>;base64,<?php echo $imageData; ?>" alt="Image"
style="width:200px; height:100px;">
</td>
</tr>
<?php
}

// Close connectionmysqli_close($connection);
?>
</tbody>
</table>
</form>
</center>
</body>
</html>
OUTPUT
2. INSERTION, UPDATION AND DELETION

INSERTION
<?php
$servername = "localhost";
$username = "root"; // Replace with your database username
$password = ""; // Replace with your database password
$dbname = "employee_db";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Insert employee data


$id= 116;
$first_name = "Mageswari";
$last_name = "Jayakumar";
$email = "[email protected]";
$phone = "1000000000";
$hire_date = "2023-07-20";
$job_title = "Software developer";
$sql = "INSERT INTO employees (id, first_name, last_name, email, phone, hire_date, job_title)
VALUES ('$id', '$first_name', '$last_name', '$email', '$phone', '$hire_date', '$job_title')";
if ($conn->query($sql) === TRUE) {
echo "New employee created successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
UPDATION
<?php
$servername = "localhost";
$username = "root"; // Replace with your database username
$password = ""; // Replace with your database password
$dbname = "employee_db";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Update employee job title


$employee_id = 116; // Assume you want to update the employee with ID 1
$new_job_title = "Senior Marketing Manager";
$sql = "UPDATE employees SET job_title = '$new_job_title' WHERE id = $employee_id";
if ($conn->query($sql) === TRUE) {
echo "Employee details updated successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
DELETION
<?php
$servername = "localhost";
$username = "root"; // Replace with your database username
$password = ""; // Replace with your database password
$dbname = "employee_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Delete employee
$employee_id = 116; // Assume you want to delete the employee with ID 1
$sql = "DELETE FROM employees WHERE id = $employee_id";
if ($conn->query($sql) === TRUE) {
echo "Employee deleted successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
OUTPUT
3. JOIN OPERATIONS
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
department_id INT
);
CREATE TABLE departments (
id INT AUTO_INCREMENT PRIMARY KEY,
department_name VARCHAR(50)
);
INSERT INTO departments (department_name) VALUES ('HR'), ('IT'), ('Sales');
INSERT INTO employees (name, department_id) VALUES
('Alice', 1),
('Bob', 2),
('Charlie', NULL);
<?php
// Database connection settings
$host = 'localhost';
$dbname = 'empnew';
$username = 'root';
$password = '';
try {
// Create a new PDO instance
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// INNER JOIN
$sql_inner = "
SELECT employees.name AS employee_name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.id";
$stmt_inner = $pdo->prepare($sql_inner);
$stmt_inner->execute();
$results_inner = $stmt_inner->fetchAll(PDO::FETCH_ASSOC);
// LEFT JOIN
$sql_left = "
SELECT employees.name AS employee_name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.id ";
$stmt_left = $pdo->prepare($sql_left);
$stmt_left->execute();
$results_left = $stmt_left->fetchAll(PDO::FETCH_ASSOC);
// RIGHT JOIN
$sql_right = "
SELECT employees.name AS employee_name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.id ";
$stmt_right = $pdo->prepare($sql_right);
$stmt_right->execute();
$results_right = $stmt_right->fetchAll(PDO::FETCH_ASSOC);
// Display results
echo "<h2>INNER JOIN Results:</h2>";
if ($results_inner) {
foreach ($results_inner as $row) {
echo "Employee: " . $row['employee_name'] . " - Department: " . $row['department_name'] .
"<br>";
}
} else {
echo "No employees found.<br>";
}
echo "<h2>LEFT JOIN Results:</h2>";
if ($results_left) {
foreach ($results_left as $row) {
echo "Employee: " . $row['employee_name'] . " - Department: " . ($row['department_name'] ??
'No Department') . "<br>";
}
} else {
echo "No employees found.<br>";
}
echo "<h2>RIGHT JOIN Results:</h2>";
if ($results_right) {
foreach ($results_right as $row) {
echo "Employee: " . ($row['employee_name'] ?? 'No Employee') . " - Department: " .
$row['department_name'] . "<br>";
}
} else {
echo "No employees found.<br>";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Close the connection
$pdo = null;
?>
OUTPUT

CREATION OF EMPLOYEES TABLE

INSERTING VALUES TO EMPLOYEE TABLE

CREATION OF DEPARTMENT TABLE


INSERTING VALUES TO DEPARTMENT TABLE

JOIN OPERATIONS
4. SUB QUERIES

<?php
// Database connection details
$conn = new mysqli("localhost", "root", "", "user234");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to fetch orders of customers whose name contains 'maha'
$sql_in = "SELECT orders.id AS order_id, orders.customer_id, orders.order_date, customers.name
FROM orders
JOIN customers ON orders.customer_id = customers.id
WHERE customers.id IN (SELECT id FROM customers WHERE name LIKE '%maha%')";
$result_in = $conn->query($sql_in);
echo "<h3>Orders of customers whose name contains 'maha':</h3>";
if ($result_in->num_rows > 0) {
// Output data of each row
while($row = $result_in->fetch_assoc()) {
echo "Order ID: " . $row["order_id"] . " - Customer Name: " . $row["name"] . " - Order Date: " .
$row["order_date"] . "<br>";
}
} else {
echo "No records found for customers with 'maha' in their name.<br>";
}
// Query to fetch orders of customers whose name does NOT contain 'maha'
$sql_not_in = "SELECT orders.id AS order_id, orders.customer_id, orders.order_date,
customers.name
FROM orders
JOIN customers ON orders.customer_id = customers.id
WHERE customers.id NOT IN (SELECT id FROM customers WHERE name LIKE '%maha%')";
$result_not_in = $conn->query($sql_not_in);
echo "<h3>Orders of customers whose name does NOT contain 'maha':</h3>";
if ($result_not_in->num_rows > 0) {
// Output data of each row
while($row = $result_not_in->fetch_assoc()) {
echo "Order ID: " . $row["order_id"] . " - Customer Name: " . $row["name"] . " - Order Date: " .
$row["order_date"] . "<br>";
}
} else {
echo "No records found for customers without 'maha' in their name.<br>";
}
// Close the connection
$conn->close();
?>
OUTPUT
CREATION OF CUSTOMERS TABLE

INSERTING VALUES IN CUSTOMERS TABLE

CREATION OF ORDERS TABLE


INSERTING VALUES TO ORDERSTABLE
5. AGGREGATE FUNCTIONS

CREATE TABLE employees (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2)
);
<?php
// Database connection details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query using aggregate functions
$sql = "SELECT
COUNT(id) AS total_employees,
SUM(salary) AS total_salary,
AVG(salary) AS average_salary,
MIN(salary) AS min_salary,
MAX(salary) AS max_salary
FROM employees";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Fetch the result row
$row = $result->fetch_assoc();
// Display the results
echo "Total Employees: " . $row['total_employees'] . "<br>";
echo "Total Salary: $" . number_format($row['total_salary'], 2) . "<br>";
echo "Average Salary: $" . number_format($row['average_salary'], 2) . "<br>";
echo "Minimum Salary: $" . number_format($row['min_salary'], 2) . "<br>";
echo "Maximum Salary: $" . number_format($row['max_salary'], 2) . "<br>";
} else {
echo "No data found!";
}
// Close the connection
$conn->close();
?>
OUTPUT

CREATION OF EMPLOYEE TABLE

INSERTING VALUES TO EMPLOYEE TABLE


6. STRING, NUMERIC AND DATE FUNCTIONS
Database Structure
Table: products
CREATE TABLE products
(id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP) ENGINE=InnoDB;

<?php
// Database connection
$servername = "localhost";
$username = "root"; // replace with your username
$password = ""; // replace with your password
$dbname = "database"; // replace with your database name
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sample data insertion (optional, comment this if data already exists)
$insertData = "INSERT INTO products (name, price, created_at) VALUES
('Book', 250.60, NOW()),
('Pencil', 50.20, NOW()),
('Marker Pen', 75.01, NOW())";
$conn->query($insertData);
// STRING FUNCTIONS
echo "<h2>String Functions:</h2>";
$sql = "SELECT name,
UPPER(name) AS upper_name,
LOWER(name) AS lower_name,
LENGTH(name) AS name_length
FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"] . " - Upper: " . $row["upper_name"] .
" - Lower: " . $row["lower_name"] . " - Length: " . $row["name_length"] . "<br>";
}
} else {
echo "0 results";
}
// NUMERIC FUNCTIONS
echo "<h2>Numeric Functions:</h2>";
$sql = "SELECT price,
ROUND(price) AS rounded_price,
CEIL(price) AS ceiling_price,
FLOOR(price) AS floor_price
FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Price: $" . $row["price"] . " - Rounded: $" . $row["rounded_price"] .
" - Ceiling: $" . $row["ceiling_price"] . " - Floor: $" . $row["floor_price"] . "<br>";
}
} else {
echo "0 results";
}

// DATE FUNCTIONS
echo "<h2>Date Functions:</h2>";
$sql = "SELECT created_at,
DATE(created_at) AS creation_date,
TIME(created_at) AS creation_time,
YEAR(created_at) AS creation_year,
MONTH(created_at) AS creation_month
FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Created At: " . $row["created_at"] .
" - Date: " . $row["creation_date"] .
" - Time: " . $row["creation_time"] .
" - Year: " . $row["creation_year"] .
" - Month: " . $row["creation_month"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
OUTPUT

You might also like