Unit 4 Shot Notes
Unit 4 Shot Notes
<?php
// Method 1: Using mysqli (recommended)
$servername = "localhost";
$username = "root";
$password = "";
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
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");
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";
}
?>
<?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
)";
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')";
$first_name = "Jane";
$last_name = "Smith";
$email = "[email protected]";
$age = 19;
$grade = "B";
$stmt->execute();
echo "New record created successfully";
$stmt->close();
8. Altering Tables
php
<?php
// Add a new column
$sql = "ALTER TABLE students ADD COLUMN phone VARCHAR(15)";
$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);
?>
<?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";
}
// Count records
$sql = "SELECT COUNT(*) as total FROM students";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo "Total students: " . $row['total'];
?>
<?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;
}
$grade = "A+";
$id = 2;
$stmt->execute();
$stmt->close();
?>
<?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;
}
<?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
// Or in connection string
$conn = new mysqli("localhost", "user", "pass", "db");
$conn->set_charset("utf8mb4");
// When user goes to page2.php, the server doesn't remember they logged in
// $user_logged_in is lost!
// Multiple parameters
$url = "search.php?category=books&price_min=10&price_max=50&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
// profile.php
$user_id = $_GET['id']; // From the rewritten URL
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
// 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
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";...}
// Unserializing data
$retrieved_data = unserialize($_COOKIE["user_data"]);
echo $retrieved_data['name']; // "John Doe"
// JSON deserialization
$retrieved_json = json_decode($_COOKIE["user_json"], true);
echo $retrieved_json['email']; // "[email protected]"
// Serializing objects
class User {
public $name;
public $email;
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();
// Session configuration
ini_set('session.gc_maxlifetime', 3600); // 1 hour
ini_set('session.cookie_lifetime', 0); // Until browser closes
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;
}
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;
}
Best Practices
Security
php
// Escape output
echo htmlspecialchars($user_data, ENT_QUOTES, 'UTF-8');
Performance
php
Error Handling
php
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.