0% found this document useful (0 votes)
4 views21 pages

Unit 4 Shot Notes

The document is a comprehensive guide on PHP and MySQL, covering basics such as server connections, database creation, and data manipulation commands. It also introduces PHPMyAdmin for database management and addresses common issues like connection errors and SQL injection vulnerabilities. Additionally, it discusses methods for managing state in web applications, including cookies, serialization, and session management.

Uploaded by

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

Unit 4 Shot Notes

The document is a comprehensive guide on PHP and MySQL, covering basics such as server connections, database creation, and data manipulation commands. It also introduces PHPMyAdmin for database management and addresses common issues like connection errors and SQL injection vulnerabilities. Additionally, it discusses methods for managing state in web applications, including cookies, serialization, and session management.

Uploaded by

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

PHP and MySQL Complete Guide

Part 1: PHP and MySQL Basics


What is PHP and MySQL?
PHP: A server-side programming language that runs on web servers
MySQL: A database management system that stores and manages data
Together, they create dynamic websites that can store, retrieve, and manipulate data
Basic PHP Commands for MySQL
1. Connection to the Server
Before doing anything with MySQL, you need to connect to the database server.
php

<?php
// Method 1: Using mysqli (recommended)
$servername = "localhost";
$username = "root";
$password = "";

$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

// Method 2: Using PDO (also recommended)


try {
$pdo = new PDO("mysql:host=localhost", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>

2. Creating a Database
php

<?php
$sql = "CREATE DATABASE school_management";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
?>

3. Selecting a Database
php

<?php
// Method 1: During connection
$conn = new mysqli($servername, $username, $password, "school_management");

// Method 2: After connection


mysqli_select_db($conn, "school_management");

// Method 3: Using SQL


$conn->query("USE school_management");
?>

4. Listing Databases
php

<?php
$sql = "SHOW DATABASES";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Database: " . $row["Database"] . "<br>";
}
} else {
echo "No databases found";
}
?>

5. Listing Table Names


php

<?php
$sql = "SHOW TABLES";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Table: " . $row["Tables_in_school_management"] . "<br>";
}
} else {
echo "No tables found";
}
?>

6. Creating a Table
php

<?php
$sql = "CREATE TABLE students (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
age INT(3),
grade VARCHAR(10),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {


echo "Table students created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
?>

7. Inserting Data
php

<?php
// Method 1: Simple insert
$sql = "INSERT INTO students (first_name, last_name, email, age, grade)
VALUES ('John', 'Doe', '[email protected]', 20, 'A')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

// Method 2: Using prepared statements (safer)


$stmt = $conn->prepare("INSERT INTO students (first_name, last_name, email, age, grade
$stmt->bind_param("sssis", $first_name, $last_name, $email, $age, $grade);

$first_name = "Jane";
$last_name = "Smith";
$email = "[email protected]";
$age = 19;
$grade = "B";

$stmt->execute();
echo "New record created successfully";
$stmt->close();

// Method 3: Multiple inserts


$sql = "INSERT INTO students (first_name, last_name, email, age, grade) VALUES
('Alice', 'Johnson', '[email protected]', 21, 'A'),
('Bob', 'Wilson', '[email protected]', 22, 'B'),
('Carol', 'Davis', '[email protected]', 20, 'A')";

if ($conn->multi_query($sql) === TRUE) {


echo "Multiple records created successfully";
} else {
echo "Error: " . $conn->error;
}
?>

8. Altering Tables
php

<?php
// Add a new column
$sql = "ALTER TABLE students ADD COLUMN phone VARCHAR(15)";
$conn->query($sql);

// Modify existing column


$sql = "ALTER TABLE students MODIFY COLUMN age INT(2)";
$conn->query($sql);

// Drop a column
$sql = "ALTER TABLE students DROP COLUMN phone";
$conn->query($sql);

// Add index
$sql = "ALTER TABLE students ADD INDEX(email)";
$conn->query($sql);

// Rename table
$sql = "ALTER TABLE students RENAME TO student_records";
$conn->query($sql);
?>

9. Queries (Selecting Data)


php

<?php
// Select all records
$sql = "SELECT * FROM students";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["first_name"]. " " . $row["last_na
}
} else {
echo "0 results";
}

// Select specific columns


$sql = "SELECT first_name, last_name, email FROM students WHERE age > 20";
$result = $conn->query($sql);

// Select with conditions


$sql = "SELECT * FROM students WHERE grade = 'A' AND age BETWEEN 18 AND 25";
$result = $conn->query($sql);

// Select with ordering


$sql = "SELECT * FROM students ORDER BY last_name ASC, first_name ASC";
$result = $conn->query($sql);

// Select with limit


$sql = "SELECT * FROM students LIMIT 5";
$result = $conn->query($sql);

// Count records
$sql = "SELECT COUNT(*) as total FROM students";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo "Total students: " . $row['total'];
?>

10. Updating Data


php

<?php
// Update single record
$sql = "UPDATE students SET grade='A+' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

// Update multiple records


$sql = "UPDATE students SET grade='B+' WHERE age > 21";
$conn->query($sql);

// Update with prepared statement


$stmt = $conn->prepare("UPDATE students SET grade=? WHERE id=?");
$stmt->bind_param("si", $grade, $id);

$grade = "A+";
$id = 2;
$stmt->execute();
$stmt->close();
?>

11. Deleting Data


php

<?php
// Delete specific record
$sql = "DELETE FROM students WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

// Delete multiple records


$sql = "DELETE FROM students WHERE age < 18";
$conn->query($sql);

// Delete all records (but keep table structure)


$sql = "DELETE FROM students";
$conn->query($sql);
?>
12. Deleting Tables and Databases
php

<?php
// Delete table
$sql = "DROP TABLE students";
if ($conn->query($sql) === TRUE) {
echo "Table deleted successfully";
} else {
echo "Error deleting table: " . $conn->error;
}

// Delete database
$sql = "DROP DATABASE school_management";
if ($conn->query($sql) === TRUE) {
echo "Database deleted successfully";
} else {
echo "Error deleting database: " . $conn->error;
}
?>

Part 2: PHPMyAdmin
What is PHPMyAdmin?
PHPMyAdmin is a web-based tool that provides a graphical interface to manage MySQL databases.
Instead of writing SQL commands, you can use buttons and forms.
Features of PHPMyAdmin:
1. Visual Database Management: Create, modify, and delete databases through a web interface
2. Table Operations: Create tables, insert data, modify structure visually
3. Query Builder: Write and execute SQL queries with syntax highlighting
4. Import/Export: Backup and restore databases easily
5. User Management: Manage MySQL users and permissions
6. Monitoring: View database performance and statistics
Common PHPMyAdmin Operations:
Creating Database: Click "New" → Enter database name → Click "Create"
Creating Tables: Select database → Click "New" → Define columns and data types
Inserting Data: Select table → Click "Insert" → Fill form → Click "Go"
Browsing Data: Select table → Click "Browse" to view all records
Searching: Use "Search" tab to find specific records
Exporting: Select database → Click "Export" → Choose format (SQL, CSV, etc.)
Part 3: Common Database Bugs and Issues
1. Connection Errors
php

// Problem: Wrong credentials


$conn = new mysqli("localhost", "wrong_user", "wrong_pass", "database");

// Solution: Check credentials


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

2. SQL Injection Vulnerabilities


php

// DANGEROUS - Never do this:


$user_input = $_POST['name'];
$sql = "SELECT * FROM users WHERE name = '$user_input'";

// SAFE - Use prepared statements:


$stmt = $conn->prepare("SELECT * FROM users WHERE name = ?");
$stmt->bind_param("s", $user_input);
$stmt->execute();

3. Character Encoding Issues


php

// Set proper charset


$conn->set_charset("utf8");

// Or in connection string
$conn = new mysqli("localhost", "user", "pass", "db");
$conn->set_charset("utf8mb4");

4. Memory and Timeout Issues


php

// Increase memory limit


ini_set('memory_limit', '256M');

// Increase execution time


set_time_limit(300);

// Use LIMIT for large datasets


$sql = "SELECT * FROM large_table LIMIT 1000";

Part 4: Managing State in Web Applications


The Problem of State in Web Applications
What is State? State refers to information that needs to be remembered between different web page
requests. HTTP is "stateless," meaning each request is independent and doesn't remember previous
requests.
Why is this a problem?
php

// User logs in on page1.php


$user_logged_in = true;

// When user goes to page2.php, the server doesn't remember they logged in
// $user_logged_in is lost!

Methods to Manage State


1. Passing Information via Query Strings
Query strings are parameters added to URLs after a question mark (?).
php

// Sending data through URL


echo '<a href="profile.php?user_id=123&name=John">View Profile</a>';

// profile.php - Receiving data


<?php
$user_id = $_GET['user_id']; // Gets 123
$name = $_GET['name']; // Gets "John"

echo "Welcome " . $name . "! Your ID is " . $user_id;


?>

// Multiple parameters
$url = "search.php?category=books&price_min=10&price_max=50&sort=name";

// Receiving multiple parameters


$category = $_GET['category']; // "books"
$price_min = $_GET['price_min']; // "10"
$price_max = $_GET['price_max']; // "50"
$sort = $_GET['sort']; // "name"

Advantages:
Simple to implement
Visible to users (can bookmark)
Works without cookies
Disadvantages:
Limited data size
Data visible in URL (not secure for sensitive info)
Gets messy with lots of data
2. Passing Information via URL Path
Instead of query strings, you can embed information in the URL path itself.
php

// URL structure: /user/123/profile


// Or: /product/shoes/nike/air-max

// Using .htaccess for clean URLs


// RewriteRule ^user/([0-9]+)/profile$ profile.php?id=$1

// profile.php
$user_id = $_GET['id']; // From the rewritten URL

// Manual parsing of URL path


$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', trim($path, '/'));

// For URL: /user/123/profile


$type = $segments[0]; // "user"
$id = $segments[1]; // "123"
$action = $segments[2]; // "profile"

3. Cookies
Cookies are small pieces of data stored in the user's browser.
php

// Setting a cookie
setcookie("username", "john_doe", time() + (86400 * 30)); // 30 days
setcookie("theme", "dark", time() + (86400 * 7)); // 7 days

// Setting cookie with more options


setcookie("user_pref", "value", [
'expires' => time() + 3600,
'path' => '/',
'domain' => 'example.com',
'secure' => true, // Only over HTTPS
'httponly' => true, // Not accessible via JavaScript
'samesite' => 'Strict' // CSRF protection
]);

// Reading cookies
if (isset($_COOKIE["username"])) {
echo "Hello " . $_COOKIE["username"];
} else {
echo "Hello Guest";
}

// Deleting a cookie
setcookie("username", "", time() - 3600); // Set expiry in the past

// Practical example: Remember login


if (isset($_POST['remember_me'])) {
setcookie("remember_user", $user_id, time() + (86400 * 30));
}

// Check if user should be remembered


if (isset($_COOKIE["remember_user"]) && !isset($_SESSION['user_id'])) {
// Auto-login the user
$_SESSION['user_id'] = $_COOKIE["remember_user"];
}

4. Serialization
Serialization converts complex data structures (arrays, objects) into strings that can be stored and
transmitted.
php
// Serializing an array
$user_data = [
'id' => 123,
'name' => 'John Doe',
'email' => '[email protected]',
'preferences' => ['theme' => 'dark', 'language' => 'en']
];

$serialized = serialize($user_data);
echo $serialized;
// Output: a:4:{s:2:"id";i:123;s:4:"name";s:8:"John Doe";...}

// Storing serialized data in cookie


setcookie("user_data", $serialized, time() + 3600);

// Unserializing data
$retrieved_data = unserialize($_COOKIE["user_data"]);
echo $retrieved_data['name']; // "John Doe"

// JSON serialization (more readable)


$json_data = json_encode($user_data);
setcookie("user_json", $json_data, time() + 3600);

// JSON deserialization
$retrieved_json = json_decode($_COOKIE["user_json"], true);
echo $retrieved_json['email']; // "[email protected]"

// Serializing objects
class User {
public $name;
public $email;

public function __construct($name, $email) {


$this->name = $name;
$this->email = $email;
}
}

$user = new User("Alice", "[email protected]");


$serialized_object = serialize($user);

// Store in session or cookie


$_SESSION['user_object'] = $serialized_object;

// Retrieve and unserialize


$user_object = unserialize($_SESSION['user_object']);
echo $user_object->name; // "Alice"

5. Session State
Sessions store data on the server and use cookies to identify users.
php
// Starting a session (must be called before any output)
session_start();

// Storing data in session


$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john_doe';
$_SESSION['is_admin'] = true;

// Storing complex data


$_SESSION['cart'] = [
['product' => 'Laptop', 'price' => 999, 'quantity' => 1],
['product' => 'Mouse', 'price' => 25, 'quantity' => 2]
];

// Reading session data


if (isset($_SESSION['user_id'])) {
echo "Welcome back, User ID: " . $_SESSION['user_id'];
} else { echo "Please log in";
}

// Modifying session data


$_SESSION['last_activity'] = time();
$_SESSION['page_views'] = ($_SESSION['page_views'] ?? 0) + 1;

// Removing specific session data


unset($_SESSION['temp_data']);

// Destroying entire session


session_destroy();

// Regenerating session ID (security)


session_regenerate_id(true);

// Session configuration
ini_set('session.gc_maxlifetime', 3600); // 1 hour
ini_set('session.cookie_lifetime', 0); // Until browser closes

// Practical session example - Shopping Cart


function addToCart($product_id, $quantity) {
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}

if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id] += $quantity;
} else {
$_SESSION['cart'][$product_id] = $quantity;
}
}

function getCartTotal() {
$total = 0;
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $product_id => $quantity) {
// Get product price from database
$price = getProductPrice($product_id);
$total += $price * $quantity;
}
}
return $total;
}

// Login system with sessions


function login($username, $password) {
// Verify credentials (simplified)
$user = getUserFromDatabase($username, $password);

if ($user) {
session_regenerate_id(true); // Security
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['login_time'] = time();
return true;
}
return false;
}

function logout() {
session_start();
session_unset(); // Remove all session variables
session_destroy(); // Destroy the session
setcookie(session_name(), '', time() - 3600, '/'); // Delete session cookie
}

function isLoggedIn() {
return isset($_SESSION['user_id']);
}

// Session timeout
function checkSessionTimeout($timeout = 1800) { // 30 minutes default
if (isset($_SESSION['last_activity'])) {
if (time() - $_SESSION['last_activity'] > $timeout) {
logout();
return false;
}
}
$_SESSION['last_activity'] = time();
return true;
}

Comparison of State Management Methods


Method Use Case Advantages Disadvantages
Query Passing simple data, search Simple, bookmarkable, works Limited size, visible, not secure
Strings parameters without cookies
URL Path SEO-friendly
APIs
URLs, REST Clean URLs, SEO benefits Complex routing needed

Cookies User preferences, Persistent, client-side Size limits, can be disabled,


remember login security concerns
Sessions User authentication, Secure, server-side, large data Requires cookies, server
shopping carts resources
Serialization Complex data storage Handles arrays/objects Data integrity, security risks

Best Practices
Security
php

// Always validate and sanitize input


$user_input = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

// Use prepared statements


$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_input);

// Escape output
echo htmlspecialchars($user_data, ENT_QUOTES, 'UTF-8');

// Secure session configuration


ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
ini_set('session.use_strict_mode', 1);

Performance
php

// Close database connections


$conn->close();

// Use efficient queries


$stmt = $conn->prepare("SELECT id, name FROM users WHERE active = 1 LIMIT 100");

// Cache frequently accessed data


if (!isset($_SESSION['cached_data'])) {
$_SESSION['cached_data'] = expensiveDatabaseQuery();
}

Error Handling
php

// Always handle errors


try {
$pdo = new PDO($dsn, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
error_log("Database connection failed: " . $e->getMessage());
die("Database connection error");
}

// Validate session data


if (isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id'])) {
// Proceed with user operations
} else {
// Handle invalid session
logout();
}

This comprehensive guide covers all aspects of PHP and MySQL integration, from basic database
operations to advanced state management techniques. Each concept is explained with practical
examples that you can use in real-world applications.

You might also like