基于PHP和JSON的CRUD操作

时间:2019-06-19 06:21:23

标签: php json

我有一个包含“名称”,“图像”,“性别”和“名称”字段的表格。 我将这些表单变量存储在Json文件中。

我将图像存储在uploads文件夹中,并更新表单输入和json文件中的图像路径。

[{"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}
]

我想在需要时更新Json文件。我尝试使用以下代码编辑json文件,但是每次提交编辑表单时,它都会作为新记录进行更新。

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; ?>

如何仅编辑特定记录并在json文件中更新它?

1 个答案:

答案 0 :(得分:3)

您可以维护唯一的记录ID并在数组中搜索该ID并更新该特定数组,而无需推送新数据$array_data[] = $extra;

类似下面的

  

[{“ uid”:100,name“:” John“,” image“:” uploads / john-2019061656551615.jpg“,   “性别”:男性,“名称”:开发人员},{“ uid”:101,“名称”:“罗素”,   “图片”:“ uploads / russel-201906161515.jpg”,“性别”:男,   “ designation”:developer},{“ uid”:102,“ name”:“ Jason”,   “ image”:“ uploads / jason-20190616451657.jpg”,“ gender”:男性,   “ 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; ?>