0% found this document useful (0 votes)
18 views28 pages

WebTechnologies UNIT5

The document provides an overview of PHP as a server-side scripting language, detailing its features, usage, and integration with MySQL databases. It covers essential topics such as creating and running PHP scripts, variable types, operators, control flow, and working with forms and databases using XAMPP. Additionally, it explains the client-server model and the importance of local development environments like XAMPP and LAMP.

Uploaded by

vineetha devika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views28 pages

WebTechnologies UNIT5

The document provides an overview of PHP as a server-side scripting language, detailing its features, usage, and integration with MySQL databases. It covers essential topics such as creating and running PHP scripts, variable types, operators, control flow, and working with forms and databases using XAMPP. Additionally, it explains the client-server model and the importance of local development environments like XAMPP and LAMP.

Uploaded by

vineetha devika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

WEB TECHNOLOGIES

By

K.Ramesh
Assistant Professor
Dept. of Computer Science and Engineering
Aditya University
Surampalem
UNIT - 5

PHP & NO SQL DATABASE


INTRODUCTION
• PHP stands for "Hypertext Preprocessor"

• A server-side scripting language used for web development

• Open-source and easy to learn

• Embedded within HTML to create dynamic web pages.

Why Use PHP?


• Free & Open-Source

• Supports Multiple Databases (MySQL, PostgreSQL, etc.)

• Cross-Platform Compatibility

• Large Community Support

Example: <?php
echo "Hello, World!";
?>
Web Technologies K.Ramesh, Assistant Professor
Creating and Running PHP Script
Steps to Create a PHP Script
1. Open a text editor (VS Code, Notepad++, Sublime Text).
2. Save the file with a .php extension (e.g., index.php).
3. Write PHP code inside <?php ... ?> tags.
Example: <?php
echo "Hello, World!";
?>

Running a PHP Script


1. Install a local server (XAMPP, WAMP, or MAMP).
2. Place the PHP file in the htdocs (XAMPP) or www (WAMP) folder.
3. Start Apache Server from the control panel.
4. Open a browser and enter: http://localhost/index.php

Web Technologies K.Ramesh, Assistant Professor


Variables
• Variables store data and can be used multiple times in a script. Example:
• In PHP, a variable starts with a $ sign.
Rules for PHP Variables
• Must start with a letter or underscore (_).
• Cannot start with a number.
• Case-sensitive ($name and $Name are different).
• No special characters allowed (except _).
PHP Variable Types
1. String – "Hello, PHP!"
2. Integer – 100
3. Float – 3.14
4. Boolean – true / false
5. Array – ["Apple", "Banana", "Mango"]
6. Object – Custom data structures
Web Technologies K.Ramesh, Assistant Professor
CONSTANTS
• A constant is a variable whose value cannot be changed once it is defined. In PHP, constants are defined
using the define() function or the const keyword.
Syntax for Defining Constants
• Using define() : define("SITE_NAME", "MyWebsite");
• Using const : const MAX_USERS = 100;
Example
<?php
define("PRODUCT", "Laptop");
define("PRICE", 49999.99);
const COMPANY = "Dell";
echo "Product: " . PRODUCT . "<br>";
echo "Company: " . COMPANY . "<br>";
echo "Price: $" . PRICE . "<br>";
// PRODUCT = "Tablet"; // ❌ This will cause an error
?>
Key Points
• Constants do not start with a $ symbol.
• They are global and can be accessed anywhere.
• Their values cannot be changed after definition.
• Use uppercase names for readability (e.g., PRODUCT, COMPANY).

Web Technologies K.Ramesh, Assistant Professor


DATA TYPES
• PHP is a loosely typed language, meaning variables do not need
to be declared with a specific data type; PHP automatically
determines the type based on the assigned value."

PHP Data Types


1. Scalar Types:
Integer: Whole numbers → $quantity = 10;
Float: Decimal numbers → $price = 99.99;
String: Text values → $product = "Laptop";
Boolean: True/False → $available = true;

2. Special Types:
Array: Collection of values → ["Red", "Green", "Blue"]
Object: Instance of a class
Callable: Function as a variable
Iterable: Loops through items

3. Compound Types:
Resource: External connections like files, databases
Null: Represents a variable with no value
Web Technologies K.Ramesh, Assistant Professor
OPERATORS
• Operators in PHP are used to perform operations on variables and values.
1. Arithmetic Operators (Perform mathematical operations) +, -, 5. Increment/Decrement Operators
*, /, % ++, --
$x = 10;
$x = 5;
$y = 3;
echo ++$x; // Output: 6
echo $x + $y; // Output: 13
6. String Operator (Concatenation)
2. Assignment Operators (Assign values)
$txt1 = "Hello";
=, +=, -=, *=, /=, %=, .=
$txt2 = " World";
$x = 5;
echo $txt1 . $txt2; // Output: Hello World
$x += 3; // Equivalent to $x = $x + 3
7. Array Operators (Compare arrays)
echo $x; // Output: 8
+, ==, ===, !=, <>
3. Comparison Operators (Compare values)
$a = [1, 2, 3];
==, ===, !=, <>, !==, >, <, >=, <=
$b = [4, 5, 6];
$x = 5;
$c = $a + $b; // Union of arrays
$y = "5";
print_r($c);
echo ($x == $y); // Output: 1 (true)
8. Ternary Operator (Short if-else)
4. Logical Operators (Used for conditions)
condition ? true_value : false_value;
&&, ||, !, and, or, xor
$age = 20;
$x = true;
echo ($age >= 18) ? "Adult" : "Minor"; // Output: Adult
$y = false;
echo ($x && $y); // Output: (false)

Web Technologies K.Ramesh, Assistant Professor


Controlling Program Flow

What is Controlling Program Flow?

• Determines how a program executes based on conditions and loops.


• Helps manage decision-making, repetitions, and function executions.

Main Concepts:

• Conditional Statements – Execute code based on conditions (if, else, switch).


• Loop Statements – Repeat actions multiple times (for, while, do-while, foreach).
• Arrays – Store and manipulate collections of data (indexed, associative,
multidimensional).
• Functions – Reusable blocks of code for modular programming (user-defined, built-in).

Web Technologies K.Ramesh, Assistant Professor


Conditional Statements
• Conditional statements control decision-making in a program.
🔹 if Statement
$age = 18; 🔹 switch Statement
if ($age >= 18) {
$day = "Monday";
echo "Eligible to vote"; switch ($day) {
} case "Monday":
echo "Start of the week";
🔹 if-else Statement break;
case "Friday":
$marks = 50;
echo "Weekend is near!";
if ($marks >= 40) { break;
default:
echo "Pass";
echo "Regular day";
} else { }
echo "Fail";
}

Web Technologies K.Ramesh, Assistant Professor


Loop Statements
• Loops in PHP are used to execute a block of code multiple times until a specified condition is met. They
help automate repetitive tasks and reduce redundancy in code.

Types of Loops in PHP:


• for Loop – Runs a block of code a fixed number of times.
• while Loop – Executes code while a condition remains true.
• do-while Loop – Executes the code at least once before checking the condition.
• foreach Loop – Specifically used to iterate over arrays.
🔹 for Loop (Fixed iterations) 🔹 do-while Loop (Executes at least once)
for ($i = 1; $i <= 5; $i++) { $y = 5;
echo $i . " "; do {
} echo $y . " ";
🔹 while Loop (Runs while the condition is $y--;
true) } while ($y > 2);
$x = 1;
while ($x <= 3) { 🔹 foreach Loop (Iterates over an array)
echo $x . " "; $colors = ["Red", "Green",
$x++; "Blue"];
} foreach ($colors as $color) {
echo $color . " ";
Web Technologies K.Ramesh, Assistant Professor }
ARRAYS
• An array in PHP is a data structure that stores multiple
values in a single variable. It allows efficient data
organization and manipulation.
Types of Arrays in PHP:
• Indexed Array – Uses numeric indices (e.g., $fruits =
["Apple", "Banana", "Cherry"];).
• Associative Array – Uses named keys instead of numbers
(e.g., $student = ["name" => "John", "age" =>
20];).
• Multidimensional Array – Contains nested arrays for
complex data structures.
(e.g., $matrix = [[1, 2, 3],[4, 5, 6]]; Fig : Arrays in PHP
echo $matrix[1][2]; // Output: 6)
Web Technologies K.Ramesh, Assistant Professor
FUNCTIONS
• A function in PHP is a reusable block of code that performs a specific task. It helps in reducing redundancy
and improving code organization.
Types of Functions in PHP:
• Built-in Functions – Predefined functions like strlen(), array_push(), date(), etc.
• User-defined Functions – Custom functions created by the programmer using the function keyword.
• Recursive Functions – Functions that call themselves to solve complex problems (e.g., calculating factorial).
1. Built-in Function (Predefined in PHP)
3. Recursive Function (A function calling
$text = "Hello, PHP!"; itself)
echo strlen($text); // Output: 12 (Counts the number of characters)
function factorial($n) {
if ($n == 0) {
2. User-defined Function (Created by the programmer) return 1;
function greet($name) { }
return $n * factorial($n - 1);
return "Hello, $name!";
}
} echo factorial(5); // Output: 120
echo greet("John"); // Output: Hello, John!

Web Technologies K.Ramesh, Assistant Professor


Client-Server Scripting
• The Client-Server Model is a communication system where a client (browser) requests resources, and a
server processes and responds. It enables dynamic web applications and real-time data processing.
• Powers dynamic web apps (e.g., login systems, e-commerce).
• Ensures security by processing sensitive data on the server.
• Improves performance by reducing client-side workload.
Key Technologies:
• PHP – Server-side scripting language for handling requests.
• MySQL – Database for storing and managing data.
• Apache – Web server to host and serve web pages.
Local Development with XAMPP/LAMP:
• XAMPP (Windows, Linux, macOS) and LAMP (Linux) provide a local testing environment.
• Bundles Apache, MySQL, and PHP for easy setup.
• Allows development without an internet connection.
Web Technologies K.Ramesh, Assistant Professor
XAMPP/LAMP
• XAMPP and LAMP are software stacks used for local web development, providing a complete
environment to run PHP applications.
XAMPP (Cross-platform, Apache, MySQL, PHP, Perl)
• Works on Windows, Linux, and macOS.
• Comes with Apache (web server), MySQL (database), and PHP (server-side scripting).
• Includes phpMyAdmin for easy database management.
• Simple installation and configuration.

LAMP (Linux, Apache, MySQL, PHP)


• Used in Linux-based environments.
• Requires manual setup but provides better performance for deployment.
• Preferred for hosting live websites on Linux servers.

Why Use XAMPP/LAMP for PHP?


• Provides a local testing server before deployment.
• Eliminates the need for an active internet connection.
• Simplifies PHP, MySQL, and Apache configuration.

Web Technologies K.Ramesh, Assistant Professor


Running PHP Script in XAMPP
Steps to Run a PHP Script in XAMPP:
• Start XAMPP: Open the XAMPP Control Panel and start Apache and MySQL.
• Create a PHP File:
Save the file inside the htdocs folder (e.g., C:\xampp\htdocs\test.php).
• Write a Basic PHP Script:
<?php
echo "Hello, World! Welcome to PHP in XAMPP.";
?>
• Run in Browser:
Open a browser and visit: http://localhost/test.php
• This will display "Hello, World! Welcome to PHP in XAMPP." on the webpage, confirming that
PHP is running correctly in XAMPP.

Web Technologies K.Ramesh, Assistant Professor


SUPER GLOBALS
• Super Globals are built-in PHP variables that are accessible from any part of the script (functions,
classes, or files) without needing to declare them as global.

Web Technologies K.Ramesh, Assistant Professor


Working with Form Data
• Forms collect user input and send it to a server via
GET/POST.
Key Attributes:
• action → Specifies the server-side script to process data.
• method → Defines data submission type (GET or POST).

Example:
<form action="process.php" method="POST">
<input type="text" name="username"
placeholder="Enter Name">
<input type="submit" value="Submit">
</form> Fig : PHP Form Handling Workflow

Web Technologies K.Ramesh, Assistant Professor


Database Connectivity - MySQL using XAMPP
🔹 MySQL:A popular Relational Database Management System (RDBMS) for storing structured data.
🔹 XAMPP: A free, open-source package including Apache, MySQL, PHP, and Perl.
🔹 MySQL in Command Mode:
1. Open XAMPP Shell.
2. Type mysql -u root -p to log in.
3. Run SQL commands like:
SHOW DATABASES;
USE myDB;
CREATE TABLE users (id INT, name VARCHAR(50));
🔹 MySQL in GUI (phpMyAdmin):
1. Open http://localhost/phpmyadmin/ in a browser.
2. Create & manage databases visually.
3. Execute SQL queries easily.
Web Technologies K.Ramesh, Assistant Professor
Working with MySQL Queries
🔹 SQL Query: A command used to interact with MySQL databases (retrieve, insert, update, or delete data).
🔹 Common MySQL Queries:

Creating a Database Inserting Data


Ex:CREATE DATABASE myDB; Ex: INSERT INTO users (id, name, email)
USE myDB; VALUES (1, 'John Doe', '[email protected]');

Creating a Table Retrieving Data


Ex: CREATE TABLE users ( Ex: SELECT * FROM users;
id INT PRIMARY KEY, SELECT name FROM users WHERE id = 1;
name VARCHAR(50),
email VARCHAR(100) Updating Data
); Ex: UPDATE users SET email =
'[email protected]' WHERE id = 1;

🔹 Executing Queries: Deleting Data


Ex: DELETE FROM users WHERE id = 1;
Use MySQL Command Line or phpMyAdmin in XAMPP.

Web Technologies K.Ramesh, Assistant Professor


Integrating PHP & MySQL with Form Data
Steps to Integrate PHP & MySQL with Form Data
1. Install XAMPP & Start MySQL & Apache
Open XAMPP Control Panel → Start Apache & MySQL

2. Create Database & Table (Using Command/GUI)


Command Mode: Use MySQL CLI 4. Write PHP Script to Connect & Insert Data
<?php
CREATE DATABASE myDB;
$conn = new mysqli("localhost", "root", "",
USE myDB; "myDB");
CREATE TABLE users (id INT AUTO_INCREMENT $conn->query("INSERT INTO users (name,
PRIMARY KEY, name VARCHAR(50), email email) VALUES ('$_POST[name]',
VARCHAR(100)); '$_POST[email]')");
GUI Mode: Use phpMyAdmin ?>

3. Create HTML Form 5. Run & Test


<form action="process.php" method="POST">
<input type="text" name="name"
• Save files in htdocs
required> • Open http://localhost/form.html in the browser
<input type="email" name="email" • Submit data & check database using
required>
MySQL/phpMyAdmin
<input type="submit">
</form>
Web Technologies K.Ramesh, Assistant Professor
NoSQL Database - MongoDB Introduction
NoSQL Database
• NoSQL (Not Only SQL) is a non-relational database system designed for scalability,
flexibility, and high performance.
• Used for big data, real-time applications, and distributed systems.
Types of NoSQL databases: Document-based, Key-Value, Column-Family, Graph
Databases.

MongoDB
• MongoDB is a document-oriented NoSQL database that stores data in JSON-like
BSON format.
• Provides high availability, scalability, and flexibility.
• Uses collections (similar to tables in SQL) and documents (similar to rows in SQL).

Key Features of MongoDB:


• Schema-less: No predefined schema, making it flexible.
• Scalability: Supports horizontal scaling with sharding.
• High Performance: Faster read/write operations.
• Indexing: Supports various indexing techniques for quick data retrieval. Fig: MongoDB Database Structure
• Replication: Ensures data availability with Replica Sets.

Web Technologies K. Ramesh, Assistant Professor


Create and Drop Database in MongoDB
1. Creating a Database
• Use “use myDatabase” to switch or create a database.
• MongoDB creates it only after inserting data.
Example:
use schoolDB
db.students.insertOne({ name: "Alice", age: 22 })

2. Viewing Databases
Use “show dbs” to list databases (only if they contain data).

3. Dropping a Database
• Switch to the database and drop it using:
use schoolDB
db.dropDatabase()
🔹 Deletes the database and collections permanently.

Key Points
• Databases are created when data is inserted.
• show dbs lists databases with collections.
• db.dropDatabase() removes a database permanently.
Web Technologies K. Ramesh, Assistant Professor
Create and Drop Collection in MongoDB
1. Creating a Collection
• In MongoDB, collections are created automatically when you insert the first document.
• However, you can explicitly create a collection using:
db.createCollection("students")
Example (Inserting data creates a collection automatically):
db.students.insertOne({ name: "Alice", age: 22 })

2. Viewing Collections
• To list all collections in the current database:
show collections

3. Dropping a Collection
• To delete a collection permanently, use:
db.students.drop()
• This removes all documents and deletes the collection.

Key Points
• Collections are created when data is inserted.
• show collections lists all collections in the current database.
• db.collection.drop() permanently deletes a collection.
Web Technologies K. Ramesh, Assistant Professor
MongoDB Data Types
• MongoDB supports various data types that can be used to store different kinds of values in documents.

Web Technologies K. Ramesh, Assistant Professor


MongoDB CRUD Operations

Web Technologies K. Ramesh, Assistant Professor


Integrating PHP with MongoDB.
• Install MongoDB PHP Driver
Using Composer: composer require mongodb/mongodb
Manually: sudo pecl install mongodb
echo "extension=mongodb.so" >> /etc/php.ini
• Connect to MongoDB
require 'vendor/autoload.php';
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->selectDatabase("myDB")->selectCollection("users");
• Insert Data
$document = ["name" => "Alice", "age" => 25, "email" =>
"[email protected]"];
$collection->insertOne($document);
• Query Data
$cursor = $collection->find(["age" => 25]);
foreach ($cursor as $doc) echo $doc["name"] . " - " . $doc["email"] .
"<br>";
• Update Data
$collection->updateOne(["name" => "Alice"], ['$set' => ["age" => 26]]);
• Delete Data
$collection->deleteOne(["name" => "Alice"]);
• Close Connection (Optional)
$client = null;
Web Technologies K. Ramesh, Assistant Professor
CONCLUSION

🔹 PHP – A versatile server-side scripting language for dynamic web applications.


🔹 MySQL – A structured, relational database for efficient data management.
🔹 MongoDB – A flexible NoSQL database for handling large-scale, unstructured data.
🔹 XAMPP/LAMP – Simplifies local development and testing environments.
🔹 Seamless Integration – Combining PHP with MySQL & MongoDB enables scalable, efficient, and high-
performing web solutions.

 PHP + MySQL: Used for structured data storage with tables, queries, and relationships.
 PHP + MongoDB: NoSQL database for flexible and scalable data storage.
 Client-Server Flow: PHP processes requests, interacts with databases, and returns responses to users.

Web Technologies K. Ramesh, Assistant Professor

You might also like