Unit 3 Notes: PHP & MERN Stack
PHP: Introduction and Syntax
PHP (Hypertext Preprocessor) is a server-side scripting language widely used for web
development.
PHP files have extension .php and can include HTML, CSS, JavaScript and PHP code.
Example:
<?php echo 'Hello, World!'; ?>
PHP: Decision Making and Looping
PHP supports conditional and looping constructs: if, if-else, switch, for, while, do-while.
Example - if statement:
<?php
$x = 10;
if ($x > 5) {
echo 'Greater than 5';
}
?>
Example - for loop:
<?php
for ($i = 0; $i < 5; $i++) {
echo $i;
}
?>
PHP and HTML
PHP can be embedded within HTML to create dynamic web pages.
Example:
<html><body><h1><?php echo 'Welcome!'; ?></h1></body></html>
PHP Arrays
PHP arrays store multiple values: Indexed, Associative, and Multidimensional.
Example:
$arr = array('a', 'b', 'c');
echo $arr[0]; // a
PHP Functions
Functions in PHP are declared using the function keyword.
Example:
function greet($name) {
return "Hello $name!";
}
Browser Control and Detection
Detect browser info using $_SERVER['HTTP_USER_AGENT'].
Redirect using header(): header('Location: http://example.com');
String Handling in PHP
PHP provides many string functions like strlen(), str_replace().
Example:
$str = 'Hello';
echo strlen($str); // 5
Form Processing in PHP
PHP can handle form data using $_GET and $_POST.
Example:
<form method='post'><input name='name'></form>
<?php echo $_POST['name']; ?>
File Handling in PHP
File handling using fopen(), fread(), fwrite(), fclose().
Example:
$handle = fopen('file.txt', 'r');
echo fread($handle, filesize('file.txt'));
Cookies and Sessions in PHP
Cookies store data on the client: setcookie('user', 'John', time()+3600);
Sessions store data on the server: session_start(); $_SESSION['user'] = 'John';
PHP with Databases
Use MySQLi or PDO for database interaction.
Example:
$conn = new mysqli('localhost', 'root', '', 'myDB');
$result = $conn->query('SELECT * FROM users');
MERN Stack: Introduction
MERN = MongoDB, Express.js, React.js, Node.js (Full Stack JavaScript Framework)
MongoDB Basics
MongoDB: NoSQL database that stores JSON-like documents.
Example document: { name: 'John', age: 30 }
Express.js Basics
Express.js: Minimal Node.js framework for creating APIs and routes.
Example:
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello'));
Node.js Basics
Node.js: JavaScript runtime to run JS on the server.
Example:
const http = require('http');
http.createServer((req, res) => res.end('Hi')).listen(3000);
React.js Basics
React.js: Frontend library to create UI using components.
Single Page Application (SPA) framework.