CRUD Operation in MySQL Using PHP - Insert Data

CRUD Operation in MySQL Using PHP - Insert Data

In this article, we will talk about the PHP Crud operation,  in this article we will know "how to insert the data in the database using PHP".  This article is the first article of the "PHP Crud Operation". 

PHP Crud Operation

Get Source Code

Create The form

In this step, we create the form using HTML, and CSS, with Bootstrap or without Bootstrap, I have used Bootstrap for creating the form.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rays Coding :- PHP Crud Operation</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <link rel="stylesheet" href="../css/style.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-dark">
                        <h4 class="text-center text-light">Rays Coding : PHP CRUD Operation</h4>
                    </div>
                    <div class="card-body">
                        <form action="../insert/insert.php" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="username" class="form-label">Name</label>
                                        <input type="text" class="form-control" id="username" name="user_name" placeholder="Enter User Name" autocomplete="off">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="useremail" class="form-label">Email</label>
                                        <input type="email" class="form-control" id="useremail" name="user_email" placeholder="Enter Email Address" autocomplete="off">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="usercontact" class="form-label">Mobile Number</label>
                                        <input type="text" class="form-control" id="usercontact" name="user_contact" placeholder="Enter Contact Number" autocomplete="off">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="userprofile" class="form-label">Profile</label>
                                        <input type="file" class="form-control" id="userprofile" name="user_profile" autocomplete="off">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="userpassword" class="form-label">Create Password</label>
                                        <input type="password" class="form-control" id="userpassword" name="user_password" placeholder="Create Password" autocomplete="off">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="userpassword" class="form-label">Confirm Password</label>
                                        <input type="password" class="form-control" id="userpassword" name="confirm_user_password" placeholder="Re-Enter Password" autocomplete="off">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6"></div>
                                <div class="col-md-6">
                                    <button type="submit" name="submit_btn" class="btn bg-dark text-light submit_button"><b>Submit</b></button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

This HTML code defines a web form for a PHP CRUD (Create, Read, Update, Delete) operation, incorporating Bootstrap for styling. The document includes the necessary meta tags for the character set and viewport settings. The form itself is enclosed within a Bootstrap-styled card and captures user information for insertion into a database. It collects details such as name, email, mobile number, profile picture, and password. The password field is divided into two parts for enhanced security - one for creating a password and the other for confirming it. The form is set to submit to a PHP script located at "../insert/insert.php" using the POST method. Bootstrap classes are used for styling, creating a visually appealing and responsive user interface. This form structure provides a foundation for handling user input and performing CRUD operations in a PHP application.

Additionally, the HTML code adheres to a responsive layout, ensuring a seamless user experience across various devices. The card structure, form layout, and button styling contribute to an organized and user-friendly design. The use of Bootstrap classes enhances the visual appeal, and the inclusion of appropriate labels and placeholders provides clarity for users filling out the form. This code lays the groundwork for building a dynamic and interactive web application with PHP for handling database operations.
PHP Crud Operation

Create The Connection

<?php
    $host = 'localhost';
    $username = 'root';
    $password = '';
    $database = 'crud_operation';
    $conn   = mysqli_connect($host, $username, $password);
    mysqli_select_db($conn,$database );
?>

This PHP code snippet serves the purpose of connecting a PHP script to a MySQL database. It begins by defining variables such as $host, $username, $password, and $database, which store the necessary credentials for establishing a connection. The $host variable typically represents the hostname where the MySQL database resides, often set to 'localhost' when the database server is on the same machine as the PHP script. The $username and $password variables hold the credentials required for authentication, with 'root' commonly used as the default username during local development, and an empty string provided for the password in this case. The $database variable specifies the name of the database to which the connection should be made.

Subsequently, the mysqli_connect() function is invoked to establish the connection to the MySQL database server. This function takes the hostname, username, and password as arguments and returns a MySQL connection object stored in the $conn variable upon successful connection.

Following the connection establishment, the mysqli_select_db() function is utilized to select the desired database ($database) on the established MySQL connection ($conn). This operation ensures that subsequent database operations performed within the PHP script will be executed within the context of the specified database.

Write Insert Query

<?php
    require_once('../connection/conn.php');
    if(isset($_POST['submit_btn']))
    {
        $name = $_POST['user_name'];
        $email= $_POST['user_email'];
        $contact = $_POST['user_contact'];
        $profile = $_FILES['user_profile']['name'];
        $profile_temp = $_FILES['user_profile']['tmp_name'];
        $profile_location = '../profiles/'.$profile;
        $password = $_POST['user_password'];
        $confirm_password = $_POST['confirm_user_password'];
        if($password == $confirm_password)
        {
            $insert_data = "INSERT INTO `simple_table`(`name`, `email`, `contact`, `profile`, `password`, `confirm_password`) VALUES ('$name','$email','$contact','$profile','$password','$confirm_password')";
            move_uploaded_file($profile_temp, $profile_location);
            $insert_query = mysqli_query($conn,$insert_data);
           
            if($insert_query)
            {
                header('location:../index/index.php');
            }
            else
            {
                echo "<script>alert('Data Not Insert.'); window.history.back();</script>";
            }
        }
        else
        {
            echo "<script>alert('Password Are Not Match'); window.history.back();</script>";
        }
    }
?>

This PHP code snippet manages the processing of form submissions and the insertion of data into a MySQL database. It begins by including the 'conn.php' file, which presumably contains the necessary code to establish a connection to the MySQL database. This inclusion ensures that the database connection is available for use within this script.

Upon form submission (triggered by the presence of the 'submit_btn' POST variable), the script proceeds to extract data from various form fields, including the user's name, email, contact information, profile image, password, and confirm password. The profile image is handled separately, with its name, temporary location, and desired storage location being retrieved from the $_FILES superglobal array.

Subsequently, the script checks whether the password matches the confirmed password, ensuring data integrity before proceeding. If the passwords match, an SQL INSERT query is constructed to insert the form data into the 'simple_table' table within the database. Additionally, the script moves the uploaded profile image from its temporary location to the specified directory for permanent storage using move_uploaded_file().

The INSERT query is executed using the mysqli_query() function, and the script checks if the query execution was successful. If successful, the user is redirected to the homepage using the header() function. In case of a failed query execution, an alert message is displayed using JavaScript, notifying the user of the failure, and the user is redirected back to the previous page.

PHP Crud Operation

In the event that the passwords do not match, another alert message is displayed, informing the user of the mismatch. This ensures that the user receives appropriate feedback and can take corrective action.

This PHP code handles form submissions, validates input data, processes file uploads, executes database queries, and provides feedback to the user based on the success or failure of the database operation. Proper error handling and user feedback mechanisms are essential to ensure the integrity and usability of the application. Additionally, precautions such as data validation and sanitization should be implemented to enhance security and prevent vulnerabilities.

Post a Comment

Previous Post Next Post

Recent in Technology