Everything you need to know โ clearly explained with real code examples.
In PHP, variables start with $. PHP is loosely typed โ you don't declare the type.
<?php // Variable types $name = "Alice"; // String $age = 22; // Integer $gpa = 3.85; // Float $passed = true; // Boolean $grades = [85, 90, 78]; // Array // Output echo "Name: $name, Age: $age"; // String concatenation echo "Hello " . $name . "!"; // Useful functions strlen($name); // string length strtoupper($name); // ALICE strtolower($name); // alice count($grades); // 3 ?>
<?php // if-else $marks = 75; if ($marks >= 80) { echo "A grade"; } elseif ($marks >= 60) { echo "B grade"; } else { echo "C grade"; } // for loop for ($i = 1; $i <= 5; $i++) { echo $i . " "; // 1 2 3 4 5 } // foreach โ great for arrays $fruits = ["apple", "mango", "banana"]; foreach ($fruits as $fruit) { echo $fruit . "<br>"; } // while loop $n = 1; while ($n <= 3) { echo $n++; } ?>
<?php // Define a function function greet($name) { return "Hello, $name!"; } echo greet("Bob"); // Hello, Bob! // Default parameter function add($a, $b = 10) { return $a + $b; } echo add(5); // 15 echo add(5, 3); // 8 ?>
<!-- HTML Form (form.html) --> <form action="process.php" method="POST"> <input type="text" name="username" placeholder="Your name"> <input type="password" name="password"> <button type="submit">Login</button> </form> <?php // process.php if ($_SERVER["REQUEST_METHOD"] == "POST") { $username = htmlspecialchars($_POST["username"]); $password = $_POST["password"]; echo "Welcome, $username"; } ?>
htmlspecialchars() converts special characters like < and > into safe HTML entities. Always use it to prevent XSS attacks when displaying user input.
<?php $error = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $email = trim($_POST["email"]); $age = $_POST["age"]; // Check empty if (empty($email)) { $error = "Email is required"; } // Validate email format elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $error = "Invalid email format"; } // Validate age is numeric elseif (!is_numeric($age) || $age < 1) { $error = "Enter a valid age"; } else { echo "Valid! Email: $email"; } } ?>
A class is a blueprint. An object is a real instance created from that blueprint. The constructor runs automatically when you create an object.
<?php class Student { // Properties (variables inside class) public $name; public $age; private $gpa; // only accessible inside class // Constructor โ called when object is created public function __construct($name, $age, $gpa) { $this->name = $name; $this->age = $age; $this->gpa = $gpa; } // Method (function inside class) public function introduce() { return "I am {$this->name}, age {$this->age}"; } // Getter for private property public function getGpa() { return $this->gpa; } } // Create objects $s1 = new Student("Alice", 21, 3.9); $s2 = new Student("Bob", 22, 3.5); echo $s1->introduce(); // I am Alice, age 21 echo $s1->getGpa(); // 3.9 ?>
A child class extends a parent class and inherits all its public/protected properties and methods. Use parent:: to call the parent constructor.
<?php class Animal { public $name; public function __construct($name) { $this->name = $name; } public function speak() { return "..."; } } // Dog EXTENDS Animal (inherits everything) class Dog extends Animal { public $breed; public function __construct($name, $breed) { parent::__construct($name); // call parent constructor $this->breed = $breed; } // Override parent method public function speak() { return "{$this->name} says: Woof!"; } } $dog = new Dog("Rex", "Labrador"); echo $dog->speak(); // Rex says: Woof! echo $dog->breed; // Labrador ?>
| Operation | SQL Statement | Purpose |
|---|---|---|
| CREATE | INSERT INTO | Add new record |
| READ | SELECT ... FROM | Fetch records |
| UPDATE | UPDATE ... SET | Modify existing record |
| DELETE | DELETE FROM | Remove record |
<?php $host = "localhost"; $user = "root"; $pass = ""; $db = "school"; $conn = new mysqli($host, $user, $pass, $db); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected!"; ?>
<?php $name = "Alice"; $age = 21; // Prepared statement (SAFE โ prevents SQL Injection) $stmt = $conn->prepare("INSERT INTO students (name, age) VALUES (?, ?)"); $stmt->bind_param("si", $name, $age); // s=string, i=integer $stmt->execute(); echo "Record inserted! ID: " . $conn->insert_id; ?>
<?php // Fetch ALL students $result = $conn->query("SELECT * FROM students"); while ($row = $result->fetch_assoc()) { echo $row["id"] . " - " . $row["name"] . "<br>"; } // Fetch ONE student by ID (prepared) $id = 1; $stmt = $conn->prepare("SELECT * FROM students WHERE id = ?"); $stmt->bind_param("i", $id); $stmt->execute(); $result = $stmt->get_result(); $student = $result->fetch_assoc(); echo $student["name"]; ?>
<?php $newName = "Alice Smith"; $id = 1; $stmt = $conn->prepare("UPDATE students SET name = ? WHERE id = ?"); $stmt->bind_param("si", $newName, $id); $stmt->execute(); echo "Updated! Rows affected: " . $stmt->affected_rows; ?>
<?php $id = 1; $stmt = $conn->prepare("DELETE FROM students WHERE id = ?"); $stmt->bind_param("i", $id); $stmt->execute(); echo "Deleted successfully!"; $conn->close(); // Always close connection ?>
Always use prepared statements (prepare + bind_param + execute) when taking user input. Never do: query("SELECT * WHERE id = $_GET['id']") โ that's SQL injection risk!
The DOM (Document Object Model) is the HTML page as a tree of objects. JavaScript can select elements and change them.
// Select elements const box = document.getElementById("myBox"); const items = document.querySelectorAll(".item"); // Change content & style box.innerHTML = "<b>Updated!</b>"; box.style.color = "red"; box.style.display = "none"; // hide // Change attribute document.getElementById("img1").src = "new.jpg";
Event listeners let you run code when something happens โ click, hover, typing, etc.
// Method 1: addEventListener (best practice) const btn = document.getElementById("myBtn"); btn.addEventListener("click", function() { alert("Button clicked!"); }); // Arrow function style btn.addEventListener("click", () => { document.getElementById("output").textContent = "Clicked!"; }); // Common events btn.addEventListener("mouseover", () => { /* hover */ }); btn.addEventListener("mouseout", () => { /* mouse leaves */ }); const input = document.getElementById("txtBox"); input.addEventListener("input", (e) => { console.log("Typed:", e.target.value); }); input.addEventListener("keydown", (e) => { if (e.key === "Enter") console.log("Enter pressed"); });
A very common pattern โ a list (array) of records (objects). You'll need to loop, filter, and display them.
// Array of objects const students = [ { id: 1, name: "Alice", gpa: 3.9 }, { id: 2, name: "Bob", gpa: 3.5 }, { id: 3, name: "Carol", gpa: 3.7 }, ]; // 1. Loop with forEach students.forEach(s => { console.log(s.name, s.gpa); }); // 2. filter โ get students with gpa > 3.6 const topStudents = students.filter(s => s.gpa > 3.6); console.log(topStudents); // Alice, Carol // 3. map โ transform into new array const names = students.map(s => s.name); console.log(names); // ["Alice", "Bob", "Carol"] // 4. find โ get FIRST match const bob = students.find(s => s.name === "Bob"); console.log(bob); // { id:2, name:"Bob", gpa:3.5 } // 5. Display in HTML const list = document.getElementById("studentList"); students.forEach(s => { list.innerHTML += `<li>${s.name} โ GPA: ${s.gpa}</li>`; });
Objects can contain other objects (or arrays) inside them. Access nested values with dot notation or bracket notation.
// Nested object const student = { name: "Alice", age: 21, address: { // nested object city: "Dhaka", zip: "1207" }, courses: [ // array inside object { code: "CS101", grade: "A" }, { code: "CS202", grade: "B+" } ] }; // Access nested data console.log(student.name); // Alice console.log(student.address.city); // Dhaka console.log(student.courses[0].code); // CS101 console.log(student.courses[1].grade); // B+ // Loop through nested array student.courses.forEach(c => { console.log(`${c.code}: ${c.grade}`); }); // Modify nested value student.address.city = "Chittagong";
<input id="search" placeholder="Search student..."> <ul id="list"></ul> <script> const students = [ { name: "Alice", dept: "CSE" }, { name: "Bob", dept: "EEE" }, { name: "Carol", dept: "CSE" }, ]; function renderList(data) { const list = document.getElementById("list"); list.innerHTML = ""; data.forEach(s => { list.innerHTML += `<li>${s.name} โ ${s.dept}</li>`; }); } renderList(students); // initial render // Live search on input event document.getElementById("search") .addEventListener("input", (e) => { const q = e.target.value.toLowerCase(); const filtered = students.filter(s => s.name.toLowerCase().includes(q) ); renderList(filtered); }); </script>
MVC stands for Model โ View โ Controller. It is a software design pattern that separates an application into three interconnected components so the code is organized, maintainable, and easy to scale.
Here's what happens step by step when a user visits yoursite.com/students:
1. User opens browser โ requests /students
2. Laravel ROUTER (routes/web.php) matches the URL:
Route::get('/students', [StudentController::class, 'index']);
3. CONTROLLER method runs (StudentController@index):
โ asks the MODEL for data
4. MODEL (Student.php - Eloquent):
โ queries the database
โ returns data to the Controller
5. CONTROLLER passes data to the VIEW:
return view('students.index', ['students' => $students]);
6. VIEW (resources/views/students/index.blade.php):
โ renders HTML with the data
โ sends the final HTML page to the user's browser
// Route โ maps URL to Controller method Route::get('/students', [StudentController::class, 'index']); Route::post('/students', [StudentController::class, 'store']);
class StudentController extends Controller { // READ โ show all students public function index() { $students = Student::all(); // Model fetches data return view('students.index', ['students' => $students]); } // CREATE โ save new student public function store(Request $request) { Student::create([ 'name' => $request->name, 'age' => $request->age, ]); return redirect()->route('students.index'); } }
class Student extends Model { // Fillable = allowed to mass-assign protected $fillable = ['name', 'age']; } // That's it! Eloquent handles all SQL automatically. // Student::all() โ SELECT * FROM students // Student::find(1) โ SELECT * FROM students WHERE id=1
<h1>All Students</h1> <ul> @foreach($students as $student) <li>{{ $student->name }} โ {{ $student->age }}</li> @endforeach </ul>
Remember this simple sentence: "MVC separates the application into three parts โ the Model handles data, the View handles display, and the Controller handles logic and acts as the bridge between them."