简体   繁体   中英

my previously store data are automatically deleted while updating a data

I am currently working on a job portal project, where I can store user information, in my project after registration, user can go there dashboard, and update there remaining form like, education detail and company detail. but after that when user like to update one of the any field in form, it can update that field but it can delete my remaining field, in education detail field or company detail field. What kind of this problem is occurred ?

updateprofile.php

    <?php
session_start();
if(empty($_SESSION['id_user']))
{
  header("Location: ../index.php");
  exit();
}
require_once("../db.php");

if(isset($_POST))
{
    //Escape Special Characters
    $firstname = $conn->real_escape_string( $_POST['fname']);
    $lastname = $conn->real_escape_string($_POST['lname']);
    $gender = $conn->real_escape_string($_POST['gender']);
    $contactno = $conn->real_escape_string($_POST['contactno']);
    $address = $conn->real_escape_string($_POST['address']);
    $city = $conn->real_escape_string($_POST['city']);
    $state = $conn->real_escape_string($_POST['state']);
    $aboutme = $conn->real_escape_string($_POST['aboutme']);
    $qualification = $conn->real_escape_string($_POST['qualification']);
    $stream = $conn->real_escape_string($_POST['stream']);
    $coursetype = $conn->real_escape_string($_POST['coursetype']);
    $university = $conn->real_escape_string($_POST['university']);
    $passingyear = $conn->real_escape_string($_POST['passingyear']);
    $skill = $conn->real_escape_string($_POST['skill']);
    $industry = $conn->real_escape_string($_POST['industry']);
    $functional_area = $conn->real_escape_string($_POST['functional_area']);
    $role = $conn->real_escape_string($_POST['role']);
    $is_current_job = $conn->real_escape_string($_POST['is_current_job']);
    $startdate = $conn->real_escape_string($_POST['startdate']);
    $enddate = $conn->real_escape_string($_POST['enddate']);
    $current_compname = $conn->real_escape_string($_POST['current_compname']);
    $current_salary = $conn->real_escape_string($_POST['current_salary']);
    $designation = $conn->real_escape_string($_POST['designation']);
    $notice_period = $conn->real_escape_string($_POST['notice_period']);
    $job_desc = $conn->real_escape_string($_POST['job_desc']);
    $experience = $conn->real_escape_string($_POST['experience']);
    $current_location = $conn->real_escape_string($_POST['current_location']);
    $prefer_location = $conn->real_escape_string($_POST['prefer_location']);
    $uploadOk = true;


if(is_uploaded_file($_FILES['resume']['tmp_name'])) 
    {
        $folder_dir = "../uploads/resume/";
        $base = basename($_FILES['resume']['name']); 
        $resumeFileType = pathinfo($base, PATHINFO_EXTENSION); 
        $file = uniqid() . "." . $resumeFileType;   
        $filename = $folder_dir .$file;     
        if(file_exists($_FILES['resume']['tmp_name']))      
        { 

            if($resumeFileType == "pdf")                
            {
                if($_FILES['resume']['size'] < 500000) 
                { 
                    // File size is less than 5MB
                    move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
                } 
                else 
                {
                    $_SESSION['uploadError'] = "Wrong Size of file. Max Size Allowed : 5MB";
                    header("Location: edit_profile.php");
                    exit();
                }
            } 
            else
            {
              $_SESSION['uploadError'] = "Wrong Format of file only pdf Allowed.";
              header("Location: edit_profile.php");
              exit();
            }


        }               

    } 
    else 
    {
        $uploadOk = false;
    }

    //Update User Details Query
    $sql = "UPDATE user SET firstname='$firstname', lastname='$lastname',gender='$gender',contactno='$contactno', address='$address', city='$city', state='$state',aboutme='$aboutme',qualification='$qualification', stream='$stream',coursetype='$coursetype',university='$university',passingyear='$passingyear',skill='$skill',
    industry='$industry',functional_area='$function_area',role='$role',is_current_job='$is_current_job',startdate='$startdate',enddate='$enddate',current_compname='$current_compname',current_salary='$current_salary',designation='$designation',notice_period='$notice_period',job_desc='$job_desc',experience='$experience',current_location='$current_location',prefer_location='$prefer_location'";


    if($uploadOk == true)
    {
        $sql .= ",resume='$file'";
    }
    $sql .= " WHERE id_user='$_SESSION[id_user]'";


    if($conn->query($sql) === TRUE)
    {
        //If data Updated successfully then redirect to dashboard
        header("Location: index.php");
        exit();
    }
    else 
    {
        echo "Error ". $sql . "<br>" . $conn->error;
    }

    //Close database connection.
    $conn->close();
}
else 
{
    //redirect them back to dashboard page if they didn't click update button
    header("Location: edit_profile.php");
    exit();
}

image of user table

在此处输入图片说明

Using prepared statements and dynamic field mapping to update only those fields which has value in it, here is what your code should look like

<?php
    session_start();
    if (empty($_SESSION['id_user'])) {
        header("Location: ../index.php");
        exit();
    }
    require_once("../db.php");

    if (isset($_POST)) {
        $uploadOk = true;


        if (is_uploaded_file($_FILES['resume']['tmp_name'])) {
            $folder_dir = "../uploads/resume/";
            $base = basename($_FILES['resume']['name']);
            $resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
            $file = uniqid() . "." . $resumeFileType;
            $filename = $folder_dir . $file;
            if (file_exists($_FILES['resume']['tmp_name'])) {

                if ($resumeFileType == "pdf") {
                    if ($_FILES['resume']['size'] < 500000) {
                        // File size is less than 5MB
                        move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
                    } else {
                        $_SESSION['uploadError'] = "Wrong Size of file. Max Size Allowed : 5MB";
                        header("Location: edit_profile.php");
                        exit();
                    }
                } else {
                    $_SESSION['uploadError'] = "Wrong Format of file only pdf Allowed.";
                    header("Location: edit_profile.php");
                    exit();
                }


            }

        } else {
            $uploadOk = false;
        }

        //Update User Details Query
        $postf2sqlf = array(
            'firstname'        => 'firstname',
            'lastname'         => 'lastname',
            'gender'           => 'gender',
            'contactno'        => 'contactno',
            'address'          => 'address',
            'city'             => 'city',
            'state'            => 'state',
            'aboutme'          => 'aboutme',
            'qualification'    => 'qualification',
            'stream'           => 'stream',
            'coursetype'       => 'coursetype',
            'university'       => 'university',
            'passingyear'      => 'passingyear',
            'skill'            => 'skill',
            'industry'         => 'industry',
            'functional_area'  => 'function_area',
            'role'             => 'role',
            'is_current_job'   => 'is_current_job',
            'startdate'        => 'startdate',
            'enddate'          => 'enddate',
            'current_compname' => 'current_compname',
            'current_salary'   => 'current_salary',
            'designation'      => 'designation',
            'notice_period'    => 'notice_period',
            'job_desc'         => 'job_desc',
            'experience'       => 'experience',
            'current_location' => 'current_location',
            'prefer_location'  => 'prefer_location'
        );

        $sql = 'UPDATE `user` SET ';
        $skipComma = true;
        $params = array('');
        foreach ($postf2sqlf as $p => $s) {
            if (isset($_POST[$p]) && !empty($_POST[$p])) {
                $sql .= ($skipComma ? '' : ',') . '`' . $s . '` = ?';
                $params[] = &$_POST[$p];
                $params[0] .= 's';
                $skipComma = false;
            }
        }

        if ($uploadOk == true) {
            $sql .= ",resume=?";
            $params = &$file;
            $params[0] .= 's';
        }
        $sql .= " WHERE id_user=?";
        $params[0] .= 's';
        $params[] = &$_SESSION['id_user'];

        $stmt = $db->prepare($sql);
        call_user_func_array(array($stmt, 'bind_param'), $params);
        $res = $stmt->execute();


        if ($stmt->errno == 0) {
            //If data Updated successfully then redirect to dashboard
            header("Location: index.php");
            exit();
        } else {
            echo "Error " . $sql . "<br>" . $conn->error;
        }

        //Close database connection.
        $conn->close();
    } else {
        //redirect them back to dashboard page if they didn't click update button
        header("Location: edit_profile.php");
        exit();
    }

Explanation

  • Created $postf2sqlf array, holding the Form fields as index, and sql field names as value.

  • Iterating over $postf2sqlf and checking if the index is set and not empty in $_POST , started collecting the parameters passing references in $params to use in a prepared statement to avoid SQL Injection. $params[0] holds the type (s => string) of named parameters, as mysqli_statement::bind_param requires this, and as parameters added, another s is concatenated. (For a strict sql, instead of s, other types could be used upon checking their types but for simplicity's sake I used s)

  • The reason to collect variables by passing references is because `mysqli_statement::bind_param requires the variables pass by references.

  • call_user_func_array was used to call mysqli_statement::bind_param with the $params with each index being a different argument.

  • Finally, $stmt->errno was checked against 0 (0 being no errors), to check that it was actually completed correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM