2017-04-02 230 views
0

我的PHP文件存在問題。我想將數據從我的HTML表單保存到外部JSON文件「data.json」。當我點擊按鈕保存它時,它會返回一切正常並且數據被添加的消息。不幸的是,當我檢查我的data.json文件時,它包含null而不是表單中的數據。這裏是我的代碼:PHP將null保存爲JSON文件

HTML:

<form class="form form-group" action="save.php" method="POST"> 
    <label class="control-label" for="focusedInput">Nazwa knajpy</label> 
    <input name="name" class="input form-control" id="focusedInput" type="text" value="Wpisz nazwę knajpy"> 

    <label class="control-label" for="focusedInput">Kategoria knajpy</label> 
    <input name="category" class="input form-control" id="focusedInput" type="text" value="Bar/restauracja"> 

    <label class="control-label" for="focusedInput">Adres</label> 
    <input name="addres" class="input form-control" id="focusedInput" type="text" value="Wpisz adres knajpy"> 

    <label class="control-label" for="focusedInput">Nazwa zdjęcia</label> 
    <input name="img" class="input form-control" id="focusedInput" type="text" value="Wpisz nazwę zdjęcia jpg"> 

    <label class="control-label" for="focusedInput">Cena</label> 
    <input name="price" class="input form-control" id="focusedInput" type="text" value="Wpisz cenę piwa"> 

    <input type="submit" class="btn btn-primary" value="Dodaj knajpę"> 
    </form> 

save.php:

<?php 

    $myFile = "data/data.json"; 
    $arr_data = array(); // create empty array 

    try 
    { 
     //Get form data 
     $formdata = array(
      'name'=> $_POST['name'], 
      'category'=> $_POST['category'], 
      'address'=>$_POST['address'], 
      'img'=> $_POST['img'], 
      'price'=> $_POST['price'] 
     ); 

     //Get data from existing json file 
     $jsondata = file_get_contents($myFile); 

     // converts json data into array 
     $arr_data = json_decode($jsondata, true); 

     // Push user data to array 
     array_push($arr_data,$formdata); 

     //Convert updated array to JSON 
     $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT); 

     //write json data into data.json file 
     if(file_put_contents($myFile, $jsondata)) { 
      echo 'Data successfully saved'; 
     } 
     else 
      echo "error"; 

    } 
    catch (Exception $e) { 
      echo 'Caught exception: ', $e->getMessage(), "\n"; 
    } 

?> 

感謝您的幫助!

+0

開始調試 - var_dump所有變量。 –

回答

4

此行可能導致問題:$arr_data = json_decode($jsondata, true);

你應該確保你開始使用它之前,它不是空的。

你可以添加喜歡的檢查:$arr_data = !empty($jsondata) ? json_decode($jsondata, true) : array();

您可能要執行後另一個檢查,以及確保爲您希望您有一個數組。

+0

是的!有用。謝謝:)我會接受你的答案 –