hapleafacademy avatar

Share with

PHP CRUD Tutorial: Build Simple Web Application

php crud operations

Welcome to this comprehensive PHP CRUD tutorial! In this guide, we’ll walk you through the process of creating a dynamic web application using PHP and MySQL. By the end of this tutorial, you’ll have built a fully functional CRUD (Create, Read, Update, Delete) application that allows users to manage data stored in a MySQL database or you can also use PHP Zend Framework.

Introduction to PHP CRUD Tutorial Operations

CRUD operations are fundamental in database-driven applications. They represent the basic actions that users can perform on data:

  • Create: Adding new records to the database.
  • Read: Retrieving existing records from the database.
  • Update: Modifying existing records in the database.
  • Delete: Removing records from the database.

In this tutorial, we’ll implement these CRUD operations using PHP and MySQL to create a dynamic web application.

Prerequisites

Before we begin, make sure you have the following to understand PHP Crud Tutorial operations:

  • A web server with PHP support (e.g., Apache or Nginx).
  • MySQL or MariaDB installed on your server.
  • Basic knowledge of HTML, CSS, and PHP.

Step 1: Setting Up the Database

First, let’s create a MySQL database to store our data. You can use phpMyAdmin or any MySQL client of your choice. Here’s a simple SQL script to create the necessary table:

//sql

<code>CREATE DATABASE IF NOT EXISTS php_crud_tutorial;
USE php_crud_tutorial;

CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL,
    age INT NOT NULL
);
</code>

Step 2: Creating the Database Connection

Next, let’s create a PHP file to establish a connection to our MySQL database. Create a file named db.php and add the following code:

//php
<?php

$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "php_crud_tutorial";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

Replace your_username and your_password with your MySQL username and password.

Step 3: Creating the User Model

Now, let’s create a PHP class to handle CRUD operations for users. Create a file named User.php and add the following code:

//php
<code><?php

require_once 'db.php';

class User
{
    private $conn;

    public function __construct()
    {
        global $conn;
        $this->conn = $conn;
    }

    public function createUser($name, $email, $age)
    {
        $sql = "INSERT INTO users (name, email, age) VALUES ('$name', '$email', $age)";
        return $this->conn->query($sql);
    }

    public function getUsers()
    {
        $sql = "SELECT * FROM users";
        $result = $this->conn->query($sql);
        return $result->fetch_all(MYSQLI_ASSOC);
    }

    public function getUserById($id)
    {
        $sql = "SELECT * FROM users WHERE id=$id";
        $result = $this->conn->query($sql);
        return $result->fetch_assoc();
    }

    public function updateUser($id, $name, $email, $age)
    {
        $sql = "UPDATE users SET name='$name', email='$email', age=$age WHERE id=$id";
        return $this->conn->query($sql);
    }

    public function deleteUser($id)
    {
        $sql = "DELETE FROM users WHERE id=$id";
        return $this->conn->query($sql);
    }
}
</code>

Step 4: Creating the User Interface

Now, let’s create the user interface for our CRUD application. We’ll create HTML forms to add, edit, and delete users, and display a list of users.

//html
<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP CRUD Tutorial</title>
    <style>
        /* CSS styles */
    </style>
</head>
<body>
    <h1>PHP CRUD Tutorial</h1>

    <!-- Add User Form -->
    <form action="add_user.php" method="post">
        <label for="name">Name:</label><br>
        <input type="text" id="name" name="name" required><br>
        <label for="email">Email:</label><br>
        <input type="email" id="email" name="email" required><br>
        <label for="age">Age:</label><br>
        <input type="number" id="age" name="age" required><br>
        <button type="submit">Add User</button>
    </form>

    <!-- List of Users -->
    <h2>Users</h2>
    <ul>
        <?php foreach ($users as $user): ?>
            <li>
                <?php echo $user['name']; ?> (<?php echo $user['email']; ?>) - <?php echo $user['age']; ?> years old
                <a href="edit_user.php?id=<?php echo $user['id']; ?>">Edit</a>
                <a href="delete_user.php?id=<?php echo $user['id']; ?>" onclick="return confirm('Are you sure?')">Delete</a>
            </li>
        <?php endforeach; ?>
    </ul>
</body>
</html>
</code>

Step 5: Implementing CRUD Operations

Now, let’s implement the PHP scripts to handle CRUD operations.

Add User (add_user.php)

//php
<code><?php

require_once 'User.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $user = new User();
    $user->createUser($_POST['name'], $_POST['email'], $_POST['age']);
    header("Location: index.php");
    exit();
}
</code>

Edit User (edit_user.php)

//php
<code><?php

require_once 'User.php';

if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['id'])) {
    $user = new User();
    $userDetails = $user->getUserById($_GET['id']);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $user = new User();
    $user->updateUser($_POST['id'], $_POST['name'], $_POST['email'], $_POST['age']);
    header("Location: index.php");
    exit();
}
</code>

Delete User (delete_user.php)

php
<code><?php

require_once 'User.php';

if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['id'])) {
    $user = new User();
    $user->deleteUser($_GET['id']);
    header("Location: index.php");
    exit();
}
</code>

Conclusion

Congratulations! You’ve successfully built a dynamic web application with PHP CRUD functionality. You’ve learned how to create a MySQL database, establish a database connection in PHP, implement CRUD operations using a PHP class, and create a user interface with HTML forms. This is just the beginning of your journey into web development with PHP. Continue to explore and experiment with PHP and MySQL to build more complex and feature-rich applications.

This tutorial covered the basics of CRUD operations in PHP, but there’s still a lot more to learn. Dive deeper into PHP frameworks like Laravel or Symfony for more advanced features and best practices in web development. Happy coding!

100 PHP Interview Questions : PHP CRUD Tutorial

  1. What is PHP?
  2. What are the advantages of using PHP?
  3. Explain the difference between echo and print in PHP.
  4. What is a PHP variable?
  5. What are the different types of PHP variables?
  6. How do you declare a constant in PHP?
  7. What is the difference between == and === operators in PHP?
  8. Explain the purpose of php.ini file.
  9. What is the purpose of the phpinfo() function in PHP?
  10. What is a PHP session? How do you start a PHP session?
  11. How do you end a PHP session?
  12. What is a PHP cookie? How do you set a cookie in PHP?
  13. How do you retrieve the value of a cookie in PHP?
  14. Explain the purpose of the $_GET and $_POST superglobals.
  15. What is the difference between include and require in PHP?
  16. What is the purpose of isset() function in PHP?
  17. How do you redirect a user to another page in PHP?
  18. What is the difference between getenv() and $_ENV in PHP?
  19. Explain the purpose of the date() function in PHP.
  20. How do you check if a variable is an array in PHP?

Intermediate PHP Questions:

  1. What is a PHP function? How do you define a function in PHP?
  2. What is the purpose of the return statement in PHP functions?
  3. Explain the concept of variable scope in PHP.
  4. What is a PHP namespace? How do you declare a namespace in PHP?
  5. What is the difference between public, private, and protected access modifiers in PHP?
  6. How do you handle errors and exceptions in PHP?
  7. What is the purpose of the try, catch, and finally blocks in PHP?
  8. Explain the difference between strpos() and stripos() functions in PHP.
  9. How do you validate form data in PHP?
  10. What is SQL injection? How do you prevent SQL injection in PHP?
  11. What is the purpose of the mysqli extension in PHP?
  12. How do you connect to a MySQL database using PHP?
  13. What is object-oriented programming (OOP) in PHP?
  14. Explain the concept of classes and objects in PHP.
  15. What is inheritance in PHP? How do you implement inheritance in PHP classes?
  16. What are abstract classes and interfaces in PHP?
  17. What is polymorphism in PHP?
  18. Explain the purpose of autoloading in PHP.
  19. How do you implement autoloading in PHP?
  20. What is a trait in PHP? How do you use traits in PHP classes?

Advanced PHP Questions:

  1. What are anonymous functions in PHP? How do you define an anonymous function?
  2. Explain the purpose of closures in PHP.
  3. What is a generator in PHP? How do you create a generator in PHP?
  4. What are magic methods in PHP?
  5. Explain the purpose of __construct() and __destruct() methods in PHP.
  6. What is method chaining in PHP?
  7. What are namespaces aliases in PHP? How do you use them?
  8. What is a PHP trait collision? How do you resolve trait conflicts?
  9. What are traits used for in PHP?
  10. Explain the purpose of the final keyword in PHP.
  11. What is the purpose of the yield keyword in PHP?
  12. What is the difference between == and === operators in PHP when used with objects?
  13. How do you handle file uploads in PHP?
  14. What are PHP filters? How do you use PHP filters?
  15. What is the difference between mysqli and PDO extensions in PHP?
  16. How do you use prepared statements in PHP?
  17. What is a PDO statement in PHP?
  18. Explain the purpose of PDO transactions in PHP.
  19. What are the benefits of using PDO in PHP?
  20. How do you handle exceptions in PDO in PHP?
  21. What are anonymous classes in PHP?
  22. What are the advantages of using anonymous classes in PHP?
  23. What is PHP reflection? How do you use PHP reflection?
  24. What is a PHP generator delegation? How do you implement it?
  25. What are the SPL data structures in PHP? Name some of them.

PHP Frameworks and Libraries Questions:

  1. What is a PHP framework? Name some popular PHP frameworks.
  2. What is the Model-View-Controller (MVC) pattern? How do PHP frameworks implement it?
  3. What is Composer in PHP? How do you use Composer to manage dependencies?
  4. What is Laravel? What are some features of Laravel?
  5. What is Symfony? What are some components of Symfony?
  6. What is CodeIgniter? What are some features of CodeIgniter?
  7. What is Zend Framework? What are some components of Zend Framework?
  8. What is Yii? What are some features of Yii?
  9. What is Slim Framework? What are some features of Slim Framework?
  10. What is Lumen? How does it differ from Laravel?
  11. What is Phalcon? What are some features of Phalcon?
  12. What is CakePHP? What are some features of CakePHP?
  13. What is Twig? How do you use Twig in PHP projects?
  14. What is PHPUnit? How do you use PHPUnit for unit testing in PHP?
  15. What is Mockery? How do you use Mockery for mocking in PHP?

PHP Security Questions:

  1. What is cross-site scripting (XSS)? How do you prevent XSS attacks in PHP?
  2. What is cross-site request forgery (CSRF)? How do you prevent CSRF attacks in PHP?
  3. What is SQL injection? How do you prevent SQL injection attacks in PHP?
  4. What is session hijacking? How do you prevent session hijacking in PHP?
  5. What is the purpose of the password_hash() function in PHP?
  6. How do you store passwords securely in PHP?
  7. What is secure authentication? How do you implement secure authentication in PHP?
  8. What are PHP security best practices?
  9. How do you use HTTPS in PHP applications?
  10. What is the purpose of the htmlspecialchars() function in PHP?
  11. What is data validation? How do you validate user input in PHP?
  12. What is the purpose of the filter_var() function in PHP?
  13. How do you sanitize user input in PHP?
  14. What are prepared statements? How do you use prepared statements to prevent SQL injection?
  15. What is secure file upload? How do you implement secure file upload in PHP?
  16. What is the purpose of the openssl_encrypt() and openssl_decrypt() functions in PHP?
  17. How do you prevent directory traversal attacks in PHP?
  18. What is the purpose of the setcookie() function in PHP?
  19. How do you securely manage cookies in PHP?
  20. What is the PHP security model? How does it work?

These PHP interview questions cover a wide range of topics, from basic PHP concepts to advanced PHP features, frameworks, security, and best practices. They can help both interviewers gauge candidates’ knowledge and candidates prepare for PHP-related interviews.

Stay updated with the latest posts by following the HapleafAcademy WhatsApp Channel
hapleafacademy avatar
Index