NOTES(AWT)
NOTES(AWT)
NOTES
COMPILED BY:
Ms. Madhura Rao K, Assistant Professor
2024-2025
MODULE 1
PHP and MySQL
What is PHP?
PHP (Hypertext Preprocessor) is a server-side scripting language used
primarily for web development. It can also be used for general-purpose
programming.
Features of PHP
1. Platform Independent:
o PHP code runs on multiple platforms (Windows, macOS,
Linux) and integrates seamlessly with all major web servers
(Apache, Nginx, IIS).
2. Open Source:
o PHP is free to use, which makes it accessible for developers
and companies alike.
3. Embedded in HTML:
o PHP code can be embedded directly into HTML for
dynamic content generation.
4. Supports Object-Oriented Programming (OOP):
o PHP offers OOP features like classes, inheritance,
interfaces, traits, and namespaces.
5. Error Handling:
o Error reporting and exceptions: PHP supports much errors
reporting constants to generate errors and relevant warnings
at run time. For example E_ERROR, E_WARNING,
E_PARSE, E_STRICT. PHP5 supports exception handling
which is used to throw errors which can be caught at any
time.
6. Loosely typed language:
Variables in PHP
o Declared using a dollar sign ($) followed by the variable
name.
o echo is used to print the PHP statements to the output
screen.
Example:
<?php
$name = "John"; // variable assigned with value
// while loop
<?php
$count = 1;
while ($count <= 5) {
echo "Count is: $count<br>";
$count++;
ADVANCED WEB TECHNOLOGY(23SCS061) Page 4
}
?>
//do while
<?php
$count = 1;
do {
echo "Count is: $count<br>";
$count++;
} while ($count <= 5);
?>
// for loop
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Iteration: $i<br
}
?>
// foreach loop
<?php
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo "Fruit: $fruit<br>";
}
?>
Functions in PHP
A function in PHP is a reusable block of code that performs a specific
task. Functions help in organizing code, making it modular, and
avoiding repetition. Functions can accept input (parameters) and
optionally return a value.
Syntax:
function functionName($parameter1, $parameter2)
Example:
<?php
// Function definition
function greet($name) {
return "Hello, $name!";
}
// Function call
echo greet("John"); // Output: Hello, John!
?>
Arrays in PHP
An array in PHP is a data structure that can store multiple values in a
single variable. Arrays can hold a collection of values, which can be
indexed numerically or associatively.
Types of Arrays:
Indexed Array: Uses numeric keys (default).
Associative Array: Uses named keys.
Multidimensional Array: An array containing other arrays.
Example:
<?php
// Indexed array
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Output: Apple
// Associative array
$person = ["name" => "John", "age" => 25];
ADVANCED WEB TECHNOLOGY(23SCS061) Page 6
echo $person["name"]; // Output: John
// Multidimensional array
$students = [
["name" => "Alice", "grade" => 85],
["name" => "Bob", "grade" => 90]
];
echo $students[1]["name"]; // Output: Bob
?>
HTML forms are used to collect user input, and PHP is commonly used
to handle and process the form data on the server side. An HTML form
allows users to input data through various fields, such as text boxes,
checkboxes, radio buttons, and submit buttons.
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML Form Example</title>
</head>
<body>
<form action="process.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<input type="submit" value="Submit">
</form>
ADVANCED WEB TECHNOLOGY(23SCS061) Page 7
</body>
</html>
<!---HTML form-->
<!DOCTYPE html>
<html>
<head>
<!----- process.php----->
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Sanitize and retrieve data
$username = htmlspecialchars(trim($_POST["username"]));
$password = htmlspecialchars(trim($_POST["password"]));
// Validate input
if (empty($username) || empty($password)) {
echo "Both fields are required.";
} else {
// Simulate processing (e.g., database check)
if ($username == "admin" && $password == "1234") {
echo "Welcome, $username!";
} else {
echo "Invalid username or password.";
ADVANCED WEB TECHNOLOGY(23SCS061) Page 10
}
}
} else {
echo "Invalid form submission.";
}
?>
upload.php
ADVANCED WEB TECHNOLOGY(23SCS061) Page 11
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Access the uploaded file details
$file = $_FILES["file"];
// File properties
$fileName = $file["name"];
$fileTmpName = $file["tmp_name"];
$fileSize = $file["size"];
$fileError = $file["error"];
$fileType = $file["type"];
// Validate file
if ($fileError === 0) {
if (in_array($fileType, $allowedTypes)) {
if ($fileSize <= 2 * 1024 * 1024) { // 2 MB limit
// Move the file to the upload directory
$uploadDir = "uploads/";
$uploadPath = $uploadDir . basename($fileName);
if (move_uploaded_file($fileTmpName, $uploadPath)) {
echo "File uploaded successfully!<br>";
echo "File Name: $fileName<br>";
echo "File Type: $fileType<br>";
echo "File Size: " . ($fileSize / 1024) . " KB<br>";
} else {
echo "Error moving the uploaded file.";
}
} else {
echo "File size exceeds the 2 MB limit.";
ADVANCED WEB TECHNOLOGY(23SCS061) Page 12
}
} else {
echo "Invalid file type. Only JPG, PNG, and PDF files are
allowed.";
}
} else {
echo "Error uploading file. Error code: $fileError";
}
}
?>
Cookies: A cookie is a small piece of data that the server sends to the
client (browser) to store on the user's device. Cookies are used to
remember user preferences, login details, and other information.
Sessions: A session is a way to store information to be used across
multiple pages. When a user visits a website and starts a new session,
the server creates a unique session ID and stores it in a cookie on the
user’s computer. The server also creates a file on the server to store the
session variables for that user.
Example:
Start a session and cookie
<?php
// Start the session
session_start();
<?php
// Start the session
session_start();
<?php
// Start the session
session_start();
MySQL database
✓ Updating Data:
✓ Deleting Data:
DELETE FROM users WHERE username = 'john';
✓ Dropping a Table:
DROP TABLE users;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query
$sql = "INSERT INTO users (username, password) VALUES ('john',
'secure_password')";
// Close connection
$conn->close();
?>
//Retrieving a data
<?php
// Connection
$conn = new mysqli("localhost", "root", "", "my_database");
// Check connection
ADVANCED WEB TECHNOLOGY(23SCS061) Page 19
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query
$sql = "SELECT id, username FROM users";
$result = $conn->query($sql);
// Display results
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Username: " . $row["username"] .
"<br>";
}
} else {
echo "No records found";
}
// Close connection
$conn->close();
?>
//Updating a data
<?php
// Connection
$conn = new mysqli("localhost", "root", "", "my_database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Close connection
$conn->close();
?>
// Deleting a data
<?php
// Connection
$conn = new mysqli("localhost", "root", "", "my_database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query
$sql = "DELETE FROM users WHERE username='john_doe'";
// Close connection
$conn->close();
?>
a crash.
• Begin Transaction
Start a transaction before executing operations.
For example: BEGIN TRANSACTION;
conn = db.connect() // When MySQL integrated with PHP
conn.begin()
• Perform Operations
Execute the SQL queries (INSERT, UPDATE, DELETE, etc.)
within the transaction.
• Commit the Transaction
CODE SNIPPET
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password,
$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Start transaction
$conn->begin_transaction();
try {
// Execute queries
// Commit transaction
$conn->commit();
echo "Transaction committed successfully.";
} catch (Exception $e) {
// Rollback on error
$conn->rollback();
echo "Transaction failed: " . $e->getMessage();
} finally {
// Close connection
$conn->close();
}
?>
React.js Fundamentals
ADVANCED WEB TECHNOLOGY(23SCS061) Page 28
React.js is a popular JavaScript library for building user interfaces,
particularly for single-page applications (SPAs). It allows developers
to create reusable UI components and manage application state
efficiently.
Key Concepts:
1. Components
• Definition: Reusable, self-contained pieces of UI.
• Types:
o Functional Components: Simple functions returning JSX.
o Class Components: ES6 classes with additional features like
state and lifecycle methods.
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
2. JSX (JavaScript XML)
• Definition: A syntax extension that looks like HTML and allows
embedding HTML in JavaScript.
• Example:
const element = <h1>Hello, World!</h1>;
3. Props (Properties)
• Definition: Read-only data passed from a parent to a child
component.
• Example
function Greeting(props) {
componentWillUnmount() {
clearInterval(this.timerID);
}
subscriptions).
Example:
import { useEffect, useState } from "react";
function Clock() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const timer = setInterval(() => setTime(new Date()), 1000);
return () => clearInterval(timer); // Cleanup
}, []);
return <h1>{time.toLocaleTimeString()}</h1>;
}
7. Virtual DOM
• Definition: A lightweight copy of the DOM used to optimize
to handle interactions.
• Example:
function Button() {
function handleClick() {
alert("Button clicked!");
}
return <button onClick={handleClick}>Click Me</button>;
ADVANCED WEB TECHNOLOGY(23SCS061) Page 31
}
9. Conditional Rendering
• Definition: Render different UI elements based on conditions.
• Example:
function Greeting(props) {
return props.isLoggedIn ? <h1>Welcome Back!</h1> :
<h1>Please Sign In</h1>;
}
10. Routing (React Router)
• Definition: Manage navigation between views or pages in a React
app.
• Example:
What is JSX?
• JSX stands for JavaScript XML. It's an extension of the JavaScript
language based on ES6. It's translated into regular JavaScript at
runtime.
• JSX allows us to write HTML in React which makes the process
of writing HTML in your React apps much easier.
// Plain HTML
const myElement = React.createElement('h1', { style:{color:"green"}
}, 'I do not use JSX!');
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);
// JSX
const myElement = <h1>I have used JSX!</h1>;
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);
Children props
Sometimes, we might come across situations in which we need to add
a specific element to a particular instance of a component only. In those
cases, we use children props.
const BookList = () => {
return (
<div>
<Book bookName = "Cracking The Coding Interview"
author = "Gayle Laakmann McDowell">
<button> Read Now! <button/>
< Book />
<Book bookName = "The Road to Learn React"
author = "Robert Wieruch"/>
</div>
);
};
Key Props
A key is a special attribute you need to include when creating lists of
elements in React. We use keys to give an identity to elements in lists.
We need to specify an id or any unique value to each instance of a
component to keep track of their addition or removal.
const App = () => {
const numbers = [1, 2, 3, 4, 5];
return (
<>
{numbers.map((number, index) => {
return <li key={index}> {number} </li>;
})}
</>
);
};
States in React
• React components has a built-in state object.
• The state object is where you store property values that belong to
the component.
• When the state object changes, the component re-renders.
Example:
// Specify the state object in the constructor method
class Car extends React.Component {
constructor(props) {
super(props);
ADVANCED WEB TECHNOLOGY(23SCS061) Page 37
this.state = {brand: "Ford"};
}
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
}
// Add a button with an onClick event that will change the color
property
ADVANCED WEB TECHNOLOGY(23SCS061) Page 39
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
changeColor = () => {
this.setState({color: "blue"});
}
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
<button
type="button"
onClick={this.changeColor}
>Change color</button>
</div>
);
}
}