0% found this document useful (0 votes)
5 views15 pages

Simple PHP CRUD Operations Guide

The document provides a simple implementation of a CRUD application in PHP, demonstrating database connection, handling DELETE, INSERT, and UPDATE operations for products, and displaying them in a web interface. It also covers the use of foreign keys, differences between GET and POST methods, and explains cookies and sessions in PHP. Additionally, it introduces AJAX as a technique for asynchronous data loading without page refresh, highlighting its applications in web development.

Uploaded by

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

Simple PHP CRUD Operations Guide

The document provides a simple implementation of a CRUD application in PHP, demonstrating database connection, handling DELETE, INSERT, and UPDATE operations for products, and displaying them in a web interface. It also covers the use of foreign keys, differences between GET and POST methods, and explains cookies and sessions in PHP. Additionally, it introduces AJAX as a technique for asynchronous data loading without page refresh, highlighting its applications in web development.

Uploaded by

adnanyaseen716
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Simple Implementation

<!-- simple implementation -->


<?php
// 1. Database Connection (Database name is 'database')
$conn = mysqli_connect("localhost", "root", "", "database");

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// 2. Handle DELETE
if (isset($_GET['delete'])) {
$id = $_GET['delete'];
mysqli_query($conn, "DELETE FROM products WHERE id=$id");
header("Location: [Link]");
exit;
}

// 3. Handle INSERT and UPDATE


if (isset($_POST['save'])) {
$name = $_POST['name'];
$price = $_POST['price'];
$id = $_POST['id']; // Hidden ID field

if ($id) {
// Update existing record
$sql = "UPDATE products SET name='$name', price='$price'
WHERE id='$id'";
} else {
// Insert new record (ID auto-increments)
$sql = "INSERT INTO products (name, price) VALUES
('$name', '$price')";
}

mysqli_query($conn, $sql);
header("Location: [Link]");
exit;
}
// 4. Fetch data for Edit Form
$edit_mode = false;
$edit_id = "";
$edit_name = "";
$edit_price = "";

if (isset($_GET['edit'])) {
$edit_mode = true;
$edit_id = $_GET['edit'];
$result = mysqli_query($conn, "SELECT * FROM products WHERE
id=$edit_id");
$row = mysqli_fetch_assoc($result);
$edit_name = $row['name'];
$edit_price = $row['price'];
}

// 5. Fetch all products (Read)


$result = mysqli_query($conn, "SELECT * FROM products");
?>

<!DOCTYPE html>
<html>
<head>
<title>Simple Products CRUD</title>
<style>
/* Minimal CSS */
body { font-family: sans-serif; margin: 20px; }
input, select { display: block; margin-bottom: 10px;
padding: 5px; border: 1px solid #000; }
table { width: 100%; border-collapse: collapse; margin-
top: 20px; border: 1px solid #000; }
th, td { border: 1px solid #000; padding: 8px; text-
align: left; }
th { background-color: #ddd; }
</style>
</head>
<body>
<h2><?= $edit_mode ? 'Edit Product' : 'Add Product'; ?></h2>

<!-- Form -->


<form method="post" action="[Link]">
<!-- Hidden ID to track updates -->
<input type="hidden" name="id" value="<?= $edit_id; ?>">

Name:
<input type="text" name="name" value="<?= $edit_name; ?
>" required>

Price:
<input type="number" step="0.01" name="price" value="<?=
$edit_price; ?>" required>

<input type="submit" name="save" value="Save">


<?php if ($edit_mode) { ?>
<a href="[Link]">Cancel</a>
<?php } ?>
</form>

<h2>Product List</h2>

<!-- Table -->


<table>
<tr>
<!-- ID is not shown in header -->
<th>Name</th>
<th>Price</th>
<th>Actions</th>
</tr>

<?php
while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<!-- ID is not shown in rows -->
<td><?= $row['name']; ?></td>
<td><?= $row['price']; ?></td>
<td>
<!-- ID is used here for logic -->
<a href="[Link]?edit=<?= $row['id']; ?
>">Edit</a> |
<a href="[Link]?delete=<?= $row['id']; ?>"
onclick="return confirm('Delete?');">Delete</a>
</td>
</tr>
<?php } ?>
</table>

</body>
</html>

Foreign key
Implementation for foreign key

<?php
// 1. Database Connection
$conn = mysqli_connect("localhost", "root", "", "db");

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// 2. Handle DELETE
if (isset($_GET['delete'])) {
$id = $_GET['delete'];
mysqli_query($conn, "DELETE FROM products WHERE id=$id");
header("Location: [Link]");
exit;
}

// 3. Handle INSERT and UPDATE


if (isset($_POST['save'])) {
$name = $_POST['name'];
$price = $_POST['price'];
$cat_id = $_POST['cat_id'];
$id = $_POST['id'];

if ($id) {
// Update existing record
$sql = "UPDATE products SET name='$name',
price='$price', cat_id='$cat_id' WHERE id='$id'";
} else {
// Insert new record
$sql = "INSERT INTO products (name, price, cat_id)
VALUES ('$name', '$price', '$cat_id')";
}

mysqli_query($conn, $sql);
header("Location: [Link]");
exit;
}

// 4. Fetch data for Edit Form


$edit_mode = false;
$edit_id = "";
$edit_name = "";
$edit_price = "";
$edit_cat_id = "";

if (isset($_GET['edit'])) {
$edit_mode = true;
$edit_id = $_GET['edit'];
$result = mysqli_query($conn, "SELECT * FROM products WHERE
id=$edit_id");
$row = mysqli_fetch_assoc($result);
$edit_name = $row['name'];
$edit_price = $row['price'];
$edit_cat_id = $row['cat_id'];
}

// 5. Fetch all categories for the dropdown


$categories = mysqli_query($conn, "SELECT * FROM category");
// 6. Fetch all products with JOIN
$sql = "SELECT [Link], [Link], [Link],
[Link] as cat_name
FROM products
JOIN category ON products.cat_id = [Link]";
$result = mysqli_query($conn, $sql);
?>

<!DOCTYPE html>
<html>
<head>
<title>Simple Product CRUD</title>
<style>
body {
font-family: sans-serif;
margin: 20px;
}

/* Add borders and styling to input fields */


input[type="text"], input[type="number"], select {
padding: 5px;
margin-bottom: 10px;
display: block;
border: 1px solid #333; /* Added Border */
}

/* Styling the Save Button */


input[type="submit"] {
background-color: #007bff; /* Blue color */
color: white;
padding: 8px 16px;
border: none;
cursor: pointer;
margin-top: 10px;
}

/* Table Styling */
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}

th, td {
border: 1px solid #000;
padding: 8px;
text-align: left;
}

th {
background-color: #f2f2f2;
}
</style>
</head>
<body>

<h2><?php echo $edit_mode ? 'Edit Product' : 'Add New


Product'; ?></h2>

<!-- Form -->


<form method="post" action="[Link]">
<input type="hidden" name="id" value="<?php echo
$edit_id; ?>">

Name:
<input type="text" name="name" value="<?php echo
$edit_name; ?>" required>

Price:
<input type="number" step="0.01" name="price" value="<?=
$edit_price; ?>" required>

Category:
<select name="cat_id">
<?php
mysqli_data_seek($categories, 0);
while($cat = mysqli_fetch_assoc($categories)) {
?>
<option value="<?= $cat['id']; ?>"
<?php if($edit_cat_id == $cat['id']) echo
"selected"; ?>>
<?= $cat['name']; ?>
</option>
<?php } ?>
</select>

<input type="submit" name="save" value="Save">


<?php if ($edit_mode) { ?>
<a href="[Link]">Cancel</a>
<?php } ?>
</form>

<h2>Product List</h2>

<!-- Table -->


<table>
<tr>
<!-- <th>ID</th> -->
<th>Name</th>
<th>Price</th>
<th>Category</th>
<th>Actions</th>
</tr>
<?php
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<!-- <td><?= $row['id']; ?></td> -->
<td><?= $row['name']; ?></td>
<td><?= $row['price']; ?></td>
<td><?= $row['cat_name']; ?></td>
<td>
<a href="[Link]?edit=<?= $row['id']; ?
>">Edit</a> |
<a href="[Link]?delete=<?= $row['id']; ?>"
onclick="return confirm('Are you sureeee?');">Delete</a>
</td>
</tr>
<?php
}
?>
</table>

</body>
</html>

✅ GET vs POST Method in PHP

🔹 1. Visibility of Data

Method Visibility

GET Data is visible in the URL (e.g. ?name=Adnan&age=20)

POST Data is hidden and not shown in the URL

🔹 2. Security

Method Security

GET ❌ Less secure (anyone can see parameters in browser history or logs)

POST ✅ More secure (data goes inside request body)

🔹 3. Data Size Limit

Method Limit

GET Limited (around 2048 characters)

POST No practical limit (can upload files, long forms, images)

🔹 4. When It Is Used

✔ GET is commonly used for:

 Searching
 Filters

 Navigation links

 Retrieving data

 Pagination
Example:

[Link]?query=mobile

✔ POST is commonly used for:

 Login forms

 Registration forms

 File upload

 Sensitive data

 Insert/update operations

🔹 5. Effect on Browser History

Method Browser History

GET Saved in history

POST Not saved

🔹 6. Can be bookmarked?

Method Bookmarking

GET ✔ Yes, because URL contains data

POST ❌ No, it cannot be bookmarked

🔹 7. PHP Superglobals Used

Method PHP Variable

GET $_GET['name']

POST $_POST['name']
🧪 Simple code Example

✔ GET example

<!-- [Link] -->


<a href="[Link]?name=Adnan&age=20">Send</a>
// [Link]
echo $_GET['name'];
echo $_GET['age'];

✔ POST example

<form action="[Link]" method="POST">


<input type="text" name="username">
<button type="submit">Send</button>
</form>
// [Link]
echo $_POST['username'];

🧠 One-Line Summary for Viva

GET sends data in the URL, less secure, limited data, used for fetching.
POST sends data in the request body, more secure, can send large data, used for modifying data.

🍪 What Are Cookies in PHP?

Cookies are small pieces of data stored in the user’s browser.


They help websites remember information even after the user closes the browser.

✔ Example:

 Remember username

 Save language preference

 Store cart items temporarily

 Keep user logged in


✔ Cookie is stored on:

📌 Client-side (browser)

✔ Set cookie in PHP:

setcookie("username", "Adnan", time() + 3600);

🔐 What Are Sessions in PHP?

Sessions store user data on the server, not in the browser.

They are used for secure, sensitive, or temporary information.

✔ Example:

 Login details

 Shopping cart

 User authentication

 Admin dashboard login

✔ Session is stored on:

📌 Server-side

✔ Start and set session:

session_start();

$_SESSION['username'] = "Adnan";

🔥 Main Differences (Cookies vs Sessions)

Feature Cookies Sessions

Storage Location Client browser Server

Security ❌ Less secure (can be modified) ✔ More secure

Data Size Limited (4KB) No practical limit

Expiration Developer sets time Ends when browser closes (unless configured)

Speed Faster (browser read/write) Slightly slower (server processing)

Best For Non-sensitive data Sensitive data (login, authentication)


🤔 Simple Example to Understand

✔ Cookies are like:

👉 A card in your pocket


You carry it everywhere → browser carries data.

✔ Sessions are like:

👉 A file stored in the office


Only the office (server) can access it.

🧠 One-Line Viva Answer

Cookie stores data in the browser; Session stores data on the server.
Sessions are more secure and used for sensitive data, while cookies store non-sensitive preferences.

What is AJAX?

AJAX stands for Asynchronous JavaScript and XML.

It is a web development technique that allows a webpage to send and receive data from the server
without reloading the entire page.

Simple Explanation

AJAX = Load data in the background + Update part of a webpage without refreshing.

Key Idea

 Normally, every time you submit a form or request new data, the entire page reloads.

 AJAX prevents this by sending requests in the background using JavaScript.

How AJAX Works (Step-by-Step)

1. User action → e.g., typing a username or clicking a button.

2. JavaScript sends a request to the server behind the scenes.

3. The server processes the request (like PHP/MySQL).

4. The server returns data (JSON, XML, or text).

5. JavaScript updates only a specific part of the webpage.

No page reload. Smooth and fast experience.


Where AJAX Is Used in Web Development?

✅ 1. Live Search / Auto-suggest

As you type in a search bar, suggestions appear instantly.

✅ 2. Form Validation

Check if username/email already exists without reloading.

✅ 3. Updating Page Sections

Refresh only part of a page like:

 product list

 comments

 notifications

✅ 4. Fetching Data from APIs

Load weather, news, or chats dynamically.

✅ 5. Chat Applications

Messages appear instantly using AJAX polling.

✅ 6. Like/Unlike or Upvote Buttons

Update count without page refresh.

Quick Example (jQuery AJAX)

$.ajax({
url: "get_data.php",
method: "GET",
success: function(response){
$("#result").html(response);
}
});

This updates only the <div id="result"> part instead of reloading the whole page.

Final Short Points for Viva/Exam


 AJAX = Asynchronous JavaScript and XML.

 Used to send/receive data without page reload.

 Makes websites fast, dynamic, interactive.

 Often used with: JavaScript, jQuery, JSON, PHP.

 Common uses: search suggestions, chat, form validation, auto-refresh content.

You might also like