Introduction:
Welcome to our comprehensive guide on CRUD operations using PHP and MySQL with XAMPP. In this tutorial, we’ll walk you through the fundamental concepts of Create, Read, Update, and Delete operations, empowering you to build dynamic web applications and effectively interact with databases.
Create, Read, Update, and Delete.
In the context of XAMPP, which is a free and open-source cross-platform web server solution stack, including Apache, MySQL, PHP, and Perl, you can perform CRUD operations using PHP to interact with the MySQL database.
Here is an example of how you can perform CRUD operations in XAMPP MySQL using PHP:
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "your_database_name"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
Replace “your_database_name” with the name of your MySQL database.
<?php $sql = "INSERT INTO your_table_name (column1, column2, column3) VALUES ('value1', 'value2', 'value3')"; if ($conn->query($sql) === TRUE) { echo "Record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } ?>
Replace “your_table_name” with the name of your MySQL table and adjust the column names and values accordingly.
<?php $sql = "SELECT * FROM your_table_name"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. " - Column3: " . $row["column3"]. "<br>"; } } else { echo "0 results"; } ?>
<?php $sql = "UPDATE your_table_name SET column1='new_value1', column2='new_value2' WHERE your_condition"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } ?>
Replace “your_condition” with the condition for updating the specific record(s).
<?php $sql = "DELETE FROM your_table_name WHERE your_condition"; if ($conn->query($sql) === TRUE) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . $conn->error; } ?>
Replace “your_condition” with the condition for deleting the specific record(s).
<?php $conn->close(); ?>
Make sure to close the database connection when you’re done.
Remember to secure your code against SQL injection by using prepared statements, especially when dealing with user input. This example provides a basic structure, and you should adapt it to fit your specific needs and security requirements.
Let’s create another example of a CRUD application using PHP and MySQL in XAMPP.
In this example, we’ll create a basic user management system with the following features:
1.1. Open phpMyAdmin (usually accessible at:
(http://localhost/phpmyadmin/).
1.2. Create a new database named user_management_db.
1.3. Create a table named users with the following columns:
id (INT, Primary Key, Auto Increment)
username (VARCHAR)
email (VARCHAR)
created_at (TIMESTAMP, set to the current timestamp on insertion)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Management System</title> </head> <body> <h1>User Management System</h1> <!-- Form to add a new user --> <form action="create_user.php" method="post"> <label for="username">Username:</label> <input type="text" name="username" required> <br> <label for="email">Email:</label> <input type="email" name="email" required> <br> <input type="submit" value="Add User"> </form> <!-- Display all users --> <h2>All Users:</h2> <?php include "read_users.php"; ?> </body> </html>
<?php include "db_connection.php"; if ($_SERVER["REQUEST_METHOD"] == "POST") { $username = $_POST["username"]; $email = $_POST["email"]; $sql = "INSERT INTO users (username, email) VALUES ('$username', '$email')"; if ($conn->query($sql) === TRUE) { header("Location: index.php"); // Redirect back to the main page } else { echo "Error: " . $sql . "<br>" . $conn->error; } } $conn->close(); ?>
<?php include "db_connection.php"; $sql = "SELECT * FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { echo "<ul>"; while ($row = $result->fetch_assoc()) { echo "<li>{$row['username']} - {$row['email']}</li>"; } echo "</ul>"; } else { echo "No users found."; } $conn->close(); ?>
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "user_management_db"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
4.1. Save all the files in the XAMPP htdocs directory.
4.2. Access the application at:
http://localhost/your-folder-name/index.php
4.3. Add users using the form, and they should be displayed below.
Note: Put all files of this project in a folder inside the :htdocs directory
As in the previous example, this is a simple illustration. In a real-world scenario, you would need to consider security measures, error handling, and validation. Using prepared statements is also recommended for preventing SQL injection.
we will create a quiz based on the CRUD operations example.
Here are 15 questions with explanations:
A) Create, Read, Update, Delete (Correct)
B) Connect, Retrieve, Utilize, Discard
C) Copy, Remove, Update, Delete
D) Collect, Reassess, Utilize, Debug
Explanation: CRUD stands for Create, Read, Update, and Delete, representing the basic operations performed on a database.
A) create_task.php
B) read_tasks.php
C) db_connection.php (Correct)
D) index.php
Explanation: The db_connection.php file contains the code for establishing a connection to the MySQL database.
A) Display all tasks
B) Edit a task
C) Add a new task (Correct)
D) Remove a task
Explanation: The create_task.php file handles the insertion of a new task into the database.
A) <input type=”text”>
B) <textarea> (Correct)
C) <textbox>
D) <input type=”multiline”>
Explanation: The <textarea> element is used for multiline text input.
A) Use prepared statements (Correct)
B) Escape all user input
C) Avoid user input altogether
D) Use only stored procedures
Explanation: Using prepared statements helps prevent SQL injection by automatically escaping user input.
A) Add a new user
B) Display all users (Correct)
C) Edit user information
D) Remove a user
Explanation: The read_users.php file displays all users stored in the database.
A) Redirects to the login page
B) Redirects to the user profile page
C) Redirects back to the main page (Correct)
D) Redirects to the registration form
Explanation: After successfully creating a user, the code redirects back to the main page.
A) It stores the task description
B) It ensures a unique identifier for each record (Correct)
C) It determines the order of tasks
D) It is used for timestamping
Explanation: The id column with “Auto Increment” ensures a unique identifier for each record.
A) It improves database performance
B) It prevents unauthorized access
C) It ensures data integrity
D) It prevents the entry of incorrect or malicious data (Correct)
Explanation: Validation helps ensure that only correct and valid data is entered into the database.
A) GET
B) POST (Correct)
C) PUT
D) DELETE
Explanation: The POST method is commonly used for creating new records in a database.
A) Deletes all records in the users table
B) Closes the database connection (Correct)
C) Updates user information
D) Retrieves user data
Explanation: mysqli->close() closes the connection to the MySQL database.
A) Stores time in seconds
B) Stores time in milliseconds
C) Stores both date and time (Correct)
D) Stores only the date
Explanation: The TIMESTAMP data type stores both date and time information.
A) $_SESSION
B) $_GET
C) $_POST (Correct)
D) $_REQUEST
Explanation: The $_POST superglobal is used to access form data submitted using the POST method.
A) Display a message on the webpage
B) Set the content type of the response
C) Redirect the browser to a different location (Correct)
D) Print data to the console
Explanation: The header() function is used for sending raw HTTP headers, including redirects.
A) It improves query performance
B) It simplifies SQL syntax
C) It helps prevent SQL injection (Correct)
D) It allows for batch processing
Explanation: Prepared statements help prevent SQL injection by automatically escaping user input and separating it from the SQL query.**