2017-04-25 48 views
1

我有一個代碼提交數據到一個蛋糕json'數據庫',但是當我提交使用PHP。當我重新加載頁面時,當我得到它時,該文件會重複JSON文件中最後一個對象的代碼。我如何避免這種情況?如何通過php提交數據到json文件時避免重複?

這是我的PHP

if(isset($_POST["submit"])) 
{ 
     if(empty($_POST["name"])) 
     { 
      $error = "<label class='text-danger'>Enter Name</label>"; 
     } 
     else if(empty($_POST["type"])) 
     { 
      $error = "<label class='text-danger'>Enter Type</label>"; 
     } 
     else if(empty($_POST["diff"])) 
     { 
      $error = "<label class='text-danger'>Enter Difficulty</label>"; 
     } 
     else 
     { 
      if(file_exists('../../databases/cakes.json')) 
      { 
       $current_data = file_get_contents('../../databases/cakes.json'); 
       $array_data = json_decode($current_data, true); 
       $extra = array(
        'person'  =>  array(
         'name'   =>  $_POST['name'], 
         'difficulty' =>  $_POST["diff"], 
         'type'   =>  $_POST["type"], 
         'isNew'  =>  'true', 
         'isVeg'  =>  'false', 
        ) 
       ); 
       $array_data[] = $extra; 
       $final_data = json_encode($array_data); 
       if(file_put_contents('../../databases/cakes.json', $final_data)) 
       { 
        //.-. 
       } 
      } 
      else 
      { 
       $error = 'JSON File not exits'; 
      } 
     } 
} 
?> 
<body> 
<div id="layout"></div> 
<div id="content"> 
<div id="add"> 
    <div class="form-title"><h1>Add Cake</h1></div> 
    <form method="post"> 
     <?php 
     if(isset($error)) 
     { 
      echo $error; 
     } 
     ?> 
     <br /> 
     <div class="input-field"> 
      <label for="name">Cake Name</label> 
      <input type="text" name="name"/> 
     </div> 
     <br /> 
     <div class="input-field"> 
      <label for="diff">Difficulty</label> 
      <div class="select"> 
      <select name="diff" id="slct"> 
       <option>Choose an option</option> 
       <option value="male">EZ</option> 
       <option value="female">Meh</option> 
       <option value="matthew">Mildy Hard</option>  
      </select> 
      </div> 
     </div> 
     <br /> 
     <div class="input-field"> 
      <label for="type">Type</label> 
      <input type="text" name="type"/><br /> 
      <a href="#" class="pw">Need Suggestions?</a><br> 
     </div> 
     <input class="addCake" type="submit" name="submit" value="Add Cake!"/><br /> 
     <a href="#">See some other cakes</a>      
     <?php 
     if(isset($message)) 
     { 
      echo $message; 
     } 
     ?> 
    </form> 

提交作品。 結果:

[[{"cake":{"name":"tes1","diff":"EZ","type":"Deli","isNew":"true","isVeg":"false"}}]] 

但是當我重裝網頁我看到了兩個這樣的事情... 結果:

[[{"cake":{"name":"tes1","diff":"EZ","type":"Deli","isNew":"true","isVeg":"false"},{"name":"tes1","diff":"EZ","type":"Deli","isNew":"true","isVeg":"false"}}]] 
+0

。如果你重新加載頁面,它將被瀏覽器再次提交表單,所以它被插入重複。所以你需要在插入後重定向頁面 – JYoThI

回答

0

使用($_SERVER['REQUEST_METHOD'] == 'POST'),而不是($_POST["submit"])

0

$array_data = array_merge($array_data, $extra);代替$array_data[] = $extra;