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

Creating a Simple CRUD Application with PHP and MySQL

Uploaded by

hambisatiruneh66
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
5 views6 pages

Creating a Simple CRUD Application with PHP and MySQL

Uploaded by

hambisatiruneh66
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 6

BHU

College of informatics
IT department

PHP and mysql basic CRUD operation

Creating a Simple CRUD Application with PHP and MySQL

This guide will walk you through building a basic CRUD (Create, Read, Update, Delete)
application using PHP and MySQL. It demonstrates how to manage a list of tasks within a
database.

Prerequisites:

 A local development environment with PHP and MySQL set up (e.g., XAMPP)
 Basic understanding of HTML, CSS (optional, but helpful for styling)

Steps:

1. Database Setup:
o Create a database (e.g., todolist).
o Within the database, create a table named tasks with the following columns:
 id (integer, primary key, auto-increment)
 title (varchar(255))
 description (text)
 completed (boolean, default: 0)
2. Create Task (Create):
o Form (create_task.php):
 Create an HTML form with fields for task title and description
(optional).
 The form should submit data using the POST method to a script named
add_task.php.

<!DOCTYPE html>

<html>

<body>

<h2>Add a New Task</h2>

<form action="add_task.php" method="post">

<label for="title">Task Title:</label>

<input type="text" name="title" id="title" required><br>

<label for="description">Description (Optional):</label>

<textarea name="description" id="description"></textarea><br>

<button type="submit">Add Task</button>

[1]
BHU
College of informatics
IT department
</form>

</body>

</html>

Script (add_task.php):

 This script retrieves data from the form and inserts a new record into the `tasks` table.
 Use prepared statements to prevent SQL injection vulnerabilities.
<?php

$host=’localhost’;

$user=’root’;

$pswd=’’;

//Replace all the above variables with your own data.

$conn=mysqli_connect($host,$user,$pswd) or die(“Can’t connect to the server”);

Mysqli_select_db($conn, ‘todolist’);

$title = mysqli_real_escape_string($conn, $_POST['title']);

$description = isset($_POST['description']) ? mysqli_real_escape_string($conn,


$_POST['description']) : null;

$sql = "INSERT INTO tasks (title, description) VALUES (?, ?)";

$stmt = mysqli_prepare($conn, $sql);

mysqli_stmt_bind_param($stmt, "ss", $title, $description);

if (mysqli_stmt_execute($stmt)) {

echo "Task added successfully!";

header('Location: index.php'); // Redirect to task list

} else {

echo "Error: " . $sql . "<br>" . mysqli_error($conn);

mysqli_close($conn);

?>

Read Tasks (Read):

 Script (index.php):
o This script retrieves all tasks from the tasks table and displays them in a list.
o Loop through the fetched data and display each task with its title (and
optionally, description), along with options to edit or delete the task.

<?php

$host=’localhost’;

$user=’root’;

[2]
BHU
College of informatics
IT department
$pswd=’’;

//Replace all the above variables with your own data.

$conn=mysqli_connect($host,$user,$pswd) or die(“Can’t connect to the server”);

Mysqli_select_db($conn, ‘todolist’);

$sql = "SELECT * FROM tasks";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {

echo "<h2>Tasks</h2>";

echo "<table>";

echo "<tr><th>Title</th><th>Description</th><th>Action</th></tr>";

while($row = mysqli_fetch_assoc($result)) {

$completed = $row['completed'] ? 'Completed' : 'Pending';

echo "<tr><td>" . $row["title"] . "</td><td>" . $row["description"] .


"</td><td>";

echo "<a href='edit_task.php?id=" . $row["id"] . "'>Edit</a> | ";

echo "<a href='delete_task.php?id=" . $row["id"] . "'>Delete</a>";

echo "</td></tr>";

echo "</table>";

} else {

echo "No tasks found";

mysqli_close($conn);

?>

Update Task (Update):

 Form (edit_task.php):
o This page displays a pre-filled form for editing an existing task.
o It retrieves the task ID from the URL parameter (GET['id']) and fetches the
corresponding task data from the database.
o The form submits data using the POST method to update_task.php
o Form (edit_task.php): The form populates the title and description fields with the
retrieved task data.

<!DOCTYPE html>

<html>

<body>

[3]
BHU
College of informatics
IT department
<h2>Edit Task</h2>

<?php

$host=’localhost’;

$user=’root’;

$pswd=’’;

//Replace all the above variables with your own data.

$conn=mysqli_connect($host,$user,$pswd) or die(“Can’t connect to the server”);

Mysqli_select_db($conn, ‘todolist’);

$id = $_GET['id'];

$sql = "SELECT * FROM tasks WHERE id = ?";

$stmt = mysqli_prepare($conn, $sql);

mysqli_stmt_bind_param($stmt, "i", $id);

mysqli_stmt_execute($stmt);

$result = mysqli_stmt_get_result($stmt);

if (mysqli_num_rows($result) == 1) {

$task = mysqli_fetch_assoc($result);

} else {

echo "Task not found";

exit;

?>

<form action="update_task.php" method="post">

<input type="hidden" name="id" value="<?php echo $task['id']; ?>">

<label for="title">Task Title:</label>

<input type="text" name="title" id="title" value="<?php echo $task['title']; ?


>" required><br>

<label for="description">Description (Optional):</label>

<textarea name="description" id="description"><?php echo


$task['description']; ?></textarea><br>

<button type="submit">Update Task</button>

</form>

</body>

</html>

Script (update_task.php):

[4]
BHU
College of informatics
IT department
 This script retrieves updated data from the edit form and updates the corresponding
record in the tasks table.
 Use prepared statements for security.

<?php

$host=’localhost’;

$user=’root’;

$pswd=’’;

//Replace all the above variables with your own data.

$conn=mysqli_connect($host,$user,$pswd) or die(“Can’t connect to the server”);

Mysqli_select_db($conn, ‘todolist’);

$id = $_POST['id'];

$title = mysqli_real_escape_string($conn, $_POST['title']);

$description = isset($_POST['description']) ? mysqli_real_escape_string($conn,


$_POST['description']) : null;

$sql = "UPDATE tasks SET title = ?, description = ? WHERE id = ?";

$stmt = mysqli_prepare($conn, $sql);

mysqli_stmt_bind_param($stmt, "sss", $title, $description, $id);

if (mysqli_stmt_execute($stmt)) {

echo "Task updated successfully!";

header('Location: index.php'); // Redirect to task list

} else {

echo "Error: " . $sql . "<br>" . mysqli_error($conn);

mysqli_close($conn);

?>

Delete Task (Delete):

 Script (delete_task.php):
o This script retrieves the task ID from the URL parameter (GET['id']) and
deletes the corresponding record from the tasks table.
o Confirm deletion with the user before proceeding.

<?php

$host=’localhost’;

$user=’root’;

$pswd=’’;

//Replace all the above variables with your own data.

[5]
BHU
College of informatics
IT department
$conn=mysqli_connect($host,$user,$pswd) or die(“Can’t connect to the server”);

Mysqli_select_db($conn, ‘todolist’);

$id = $_GET['id'];

// Confirmation prompt (optional)

if (isset($_GET['confirm'])) {

$sql = "DELETE FROM tasks WHERE id = ?";

$stmt = mysqli_prepare($conn, $sql);

mysqli_stmt_bind_param($stmt, "i", $id);

mysqli_stmt_execute($stmt);

echo "Task deleted successfully!";

header('Location: index.php'); // Redirect to task list

} else {

// Display confirmation message

echo "Are you sure you want to delete this task?";

echo "<a href='delete_task.php?id=" . $id . "&confirm=1'>Yes</a> | ";

echo "<a href='index.php'>No</a>";

mysqli_close($conn);

?>

Remember:

 Include proper error handling and user feedback throughout your application.
 Sanitize user input to prevent security vulnerabilities.
 Close the database connection after each operation.

This CRUD application demonstrates the basic functionalities of creating, reading, updating,
and deleting data using PHP and MySQL. You can extend this example by adding features
like marking tasks as completed, sorting tasks, or implementing user authentication.

[6]

You might also like