CRUD Operation in MySQL Using PHP - Update Data In MySQL Using PHP Form

CRUD Operation in MySQL Using PHP - Update Data In MySQL Using PHP Form

We'll discuss "How to update data in MySQL using PHP" in this article. I have already uploaded the two articles on the "php crud operation ". so this is the third article on the "PHP Crud Operation".

PHP-Crud-Operation

Create an edit form and display user data

In this step, I have created an edit form to fetch the specific user data from the database using the user ID and displayed the user data in the form input box. 

<?php
    require('../connection/conn.php');
    $get_id =  $_GET['id'];
    $select_data_of_user= "SELECT * FROM `simple_table` WHERE id = $get_id";
    $select_data_query = mysqli_query($conn, $select_data_of_user);
    $selected_fetch_data = mysqli_fetch_array($select_data_query);
?>
<!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 d-flex justify-content-between">
                        <h4 class="text-center text-light">Rays Coding : PHP CRUD Operation</h4>
                        <a href="../index/index.php" class="btn bg-warning text-dark"><b>Data List</b></a>
                    </div>
                    <div class="card-body">
                        <form action="../update/update.php" method="post" enctype="multipart/form-data">
                            <input type="hidden" name="user_id" id="" value="<?php echo $selected_fetch_data['id']?>">
                            <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" value="<?php echo $selected_fetch_data['name']?>">
                                    </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" value="<?php echo $selected_fetch_data['email']?>">
                                    </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" value="<?php echo $selected_fetch_data['contact']?>">
                                    </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" value="">
                                        <img src='../profiles/<?php echo $selected_fetch_data['profile']?>'>
                                    </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" value="<?php echo $selected_fetch_data['password']?>">
                                    </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" value="<?php echo $selected_fetch_data['confirm_password']?>">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6"></div>
                                <div class="col-md-6">
                                    <button type="submit" name="update_btn" class="btn bg-dark text-light submit_button"><b>Update</b></button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Get Source Code

This HTML document presents a form for updating user data within a PHP CRUD (Create, Read, Update, Delete) application. Here's a breakdown of its components and functionality:

Document Structure: The document starts with a standard HTML5 document structure, including , , and tags. Meta tags are used to specify character encoding, viewport settings, and compatibility.

Title and Stylesheet Links: The document includes a title specifying "Rays Coding: PHP CRUD Operation" and links to external resources. It imports the Bootstrap CSS framework from a CDN (Content Delivery Network) to apply Bootstrap styles to the form elements. Additionally, a custom stylesheet (style.css) is linked to apply additional custom styles to the form if needed.

Form Content: Within the body section, the main content is wrapped inside a Bootstrap container, row, and column for proper layout and alignment. Inside a card element, the form is constructed to update user data.

Form Fields: The form includes input fields for various user attributes such as name, email, contact number, profile image, password, and confirm password. These fields are pre-populated with existing user data obtained from a PHP variable $selected_fetch_data. Each input field is enclosed within appropriate Bootstrap grid system classes to ensure proper spacing and alignment.

File Input for Profile Image: A file input field is provided for uploading a profile image. Users can select a new image file to update their profile picture. Additionally, the current profile image is displayed alongside the file input field, allowing users to preview their existing profile picture.

Submit Button: A submit button labeled "Update" is provided at the bottom of the form. Upon clicking this button, the form data will be submitted to the specified PHP script (../update/update.php) for processing and updating the user's information in the database.

JavaScript: No JavaScript code is included in this document. However, client-side validation or additional interactive features could be implemented using JavaScript if needed.

This HTML form provides a user-friendly interface for updating user data in a PHP CRUD application. It utilizes Bootstrap for styling and layout consistency, ensuring a responsive and visually appealing design.

PHP-Crud-Operation

Write update query

<?php
    require('../connection/conn.php');
    if(isset($_POST['update_btn']))
    {
        $user_id = $_POST['user_id'];
        $name = $_POST['user_name'];
        $email = $_POST['user_email'];
        $contact = $_POST['user_contact'];
        $profile = $_FILES['user_profile']['name'];
        $profile_tmp = $_FILES['user_profile']['tmp_name'];
        $profile_location = '../profiles/'.$profile;
        $password = $_POST['user_password'];
        $confirm_password = $_POST['confirm_user_password'];
        if(isset($user_id))
        {
            if($password === $confirm_password)
            {
                if($profile != '')
                {
                    $update_date = "UPDATE `simple_table` SET `name`='$name',`email`='$email',`contact`='$contact',`profile`='$profile',`password`='$password',`confirm_password`='$confirm_password'  WHERE id = $user_id";
                    $update_date_query = mysqli_query($conn ,$update_date) ;
                    if($update_date_query)
                    {
                        move_uploaded_file($profile_tmp, $profile_location);
                        header('location:../index/index.php');
                    }
                    else
                    {
                        echo "<script>alert('Data Not update Successfully'); window.history.back();</script>";
                    }
                }
                else
                {
                    $update_date = "UPDATE `simple_table` SET `name`='$name',`email`='$email',`contact`='$contact',`password`='$password',`confirm_password`='$confirm_password'  WHERE id = $user_id";
                    $update_date_query = mysqli_query($conn ,$update_date) ;
                    if($update_date_query)
                    {
                        move_uploaded_file($profile_tmp, $profile_location);
                        header('location:../index/index.php');
                    }
                    else
                    {
                        echo "<script>alert('Data Not update Successfully'); window.history.back();</script>";
                    }
                }
            }
            else
            {
                echo "<script>alert('Password Are Not Match'); window.history.back();</script>";
            }
        }
    }
?>

This PHP script handles the update functionality for user data within a CRUD (Create, Read, Update, Delete) application. Let's break down the functionality and components of the script:

Database Connection: The script begins by including the 'conn.php' file, which presumably contains the code for establishing a connection to the MySQL database. This inclusion ensures that the database connection is available for use within this script.

Form Submission Handling: The script checks if the form has been submitted by checking the existence of the 'update_btn' POST variable. This variable is typically associated with the submit button in the HTML form.

Data Retrieval: Upon form submission, the script retrieves the submitted form data using $_POST and $_FILES superglobal arrays. It fetches the user ID, name, email, contact number, profile image, password, and confirm password fields from the form.

Data Validation: The script validates whether the password matches the confirm password before proceeding with the update operation. If the passwords match, the script continues with the update process; otherwise, it displays an alert message indicating that the passwords do not match.

Update Operation: The script constructs an SQL UPDATE query to update the user's data in the database table 'simple_table'. It updates the user's name, email, contact number, profile image, and password, and confirm password fields based on the provided user ID.

File Upload: If a new profile image is uploaded, the script moves the uploaded image file from its temporary location to the specified directory using move_uploaded_file(). This ensures that the updated profile image is stored correctly on the server.

Redirection: After successfully updating the user's data in the database, the script redirects the user to the homepage ('../index/index.php') using the header() function. If the update operation fails, the script displays an alert message notifying the user of the failure and prompts them to go back to the previous page using window.history.back().

This PHP script facilitates the update of user data in a MySQL database within a CRUD application. It ensures data integrity by validating user inputs and handles file uploads for profile images. Additionally, it provides feedback to the user regarding the success or failure of the update operation, enhancing the user experience of the application.


PHP-Crud-Operation


Conclusion

In conclusion, the provided PHP code is a script designed to handle the updating of user data in a MySQL database. It first checks if a form with the name 'update_btn' has been submitted via the POST method. Upon submission, it retrieves various form inputs, including user ID, name, email, contact, profile image, password, and confirm password. The script constructs an SQL UPDATE query to modify the corresponding record in the 'simple_table' of the database. The query is conditionally constructed to include the profile image if a new one is uploaded.

Before executing the update query, the script checks if the entered password and confirm password match. If the passwords match, the script proceeds with the update, moving the uploaded profile image to a specified directory. Success leads to a redirection to 'index.php', while failure prompts an alert and a return to the previous page.

Post a Comment

Previous Post Next Post

Recent in Technology