简体   繁体   中英

PHP and JSON based CRUD operations

I had a form which has Name, Image, Gender and Designation fields. I am storing those form variables in a Json file.

I am storing the images in a uploads folder and updating the form inputs, image path in a json file.

[{"name":"John", "image":"uploads/john-2019061656551615.jpg", "gender":male, "designation":developer},
{"name":"Russel", "image":"uploads/russel-201906161515.jpg", "gender":male, "designation":developer},
{"name":"Jason", "image":"uploads/jason-20190616451657.jpg", "gender":male, "designation":developer}
]

I want update the Json file whenever it's required.I tried to edit the json file with the below code but every time when i submitting the edit form it is updating as a new record.

if (isset($_GET["id"])) {
    $id = (int) $_GET["id"];
    $getfile = file_get_contents('data.json');
    $all = json_decode($getfile, true);
    $jsonfile = $all;
    $jsonfile = $jsonfile[$id];

    $post["name"] = isset($_POST["name"]) ? $_POST["name"] : "";
    $post["gender"] = isset($_POST["gender"]) ? $_POST["gender"] : "";
    $post["fileToUpload"] = isset($_POST["fileToUpload"]) ? $_POST["fileToUpload"] : "";
    $post["designation"] = isset($_POST["designation"]) ? $_POST["designation"] : "";
}

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if(isset($_POST["submit"])) {

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";

           if(file_exists('data.json'))  
           {  
                $current_data = file_get_contents('data.json');  
                $array_data = json_decode($current_data, true);  
                $extra = array(  
                     'name'               =>     $_POST["name"],  
                     'image'               =>     $target_file,  
                     'gender'          =>     $_POST["gender"],  
                     'designation'     =>     $_POST["designation"]  
                );  
                $array_data[] = $extra;  
                $final_data = json_encode($array_data);  
                if(file_put_contents('data.json', $final_data))  
                {  
                     $message = "<label class='text-success'>File Appended Success fully</p>";  
                }
           }  
           else  
           {  
                $error = 'JSON File not exits';  
           }        
    } else {
        echo "Sorry, there was an error uploading your file.";
    }   
    }
?>
<?php if (isset($_GET["id"])): ?>
    <form action="" method="POST">
        <input type="hidden" value="<?php echo $id ?>" name="id"/>
        <input type="text" value="<?php echo $jsonfile["name"] ?>" name="name"/>
        <input type="text" value="<?php echo $jsonfile["gender"] ?>" name="gender"/>
        <input class="button button2" type="file" name="fileToUpload" id="fileToUpload">
        <input type="text" value="<?php echo $jsonfile["designation"] ?>" name="designation"/>
        <input type="submit" value="Submit" name="submit">
    </form>
<?php endif; ?>

How to edit only particular record and update it in json file ?

instead of pushing new data $array_data[] = $extra; you can maintain unique record id and search that id in array and update that specific array

something like below

[{"uid":100,name":"John", "image":"uploads/john-2019061656551615.jpg", "gender":male, "designation":developer}, {"uid":101,"name":"Russel", "image":"uploads/russel-201906161515.jpg", "gender":male, "designation":developer}, {"uid":102,"name":"Jason", "image":"uploads/jason-20190616451657.jpg", "gender":male, "designation":developer} ]

function searchForId($id, $array) {
       foreach ($array as $key => $val) {
           if ($val['uid'] === $id) {
               return $key;
           }
       }
       return null;
    }

if (isset($_GET["id"])) {
    $id = (int) $_GET["id"];
    $getfile = file_get_contents('data.json');
    $all = json_decode($getfile, true);
    $jsonfile = $all;
    $jsonfile = $jsonfile[$id];

    $post["name"] = isset($_POST["name"]) ? $_POST["name"] : "";
    $post["gender"] = isset($_POST["gender"]) ? $_POST["gender"] : "";
    $post["fileToUpload"] = isset($_POST["fileToUpload"]) ? $_POST["fileToUpload"] : "";
    $post["designation"] = isset($_POST["designation"]) ? $_POST["designation"] : "";
}

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

if(isset($_POST["submit"])) {
 if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";

           if(file_exists('data.json'))  
           {  

                $current_data = file_get_contents('data.json');  
                $array_data = json_decode($current_data, true);

                $key = searchForId($id, $array_data);
                $array_data[$key]['name']= $_POST["name"];
                $array_data[$key]['image']= $target_file;
                $array_data[$key]['gender']= $_POST["gender"];
                $array_data[$key]['designation']= $_POST["designation"];  

                $final_data = json_encode($array_data);  
                if(file_put_contents('data.json', $final_data))  
                {  
                     $message = "<label class='text-success'>File Appended Success fully</p>";  
                }
           }  
           else  
           {  
                $error = 'JSON File not exits';  
           }        
      }else {
          echo "Sorry, there was an error uploading your file.";
      }   
    }


<?php if (isset($_GET["id"])): ?>
    <form action="" method="POST">
        <input type="hidden" value="<?php echo $id ?>" name="id"/>
        <input type="text" value="<?php echo $jsonfile["name"] ?>" name="name"/>
        <input type="text" value="<?php echo $jsonfile["gender"] ?>" name="gender"/>
        <input class="button button2" type="file" name="fileToUpload" id="fileToUpload">
        <input type="text" value="<?php echo $jsonfile["designation"] ?>" name="designation"/>
        <input type="submit" value="Submit" name="submit">
    </form>
<?php endif; ?>

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