简体   繁体   中英

.json File Keeps Going Null

I Am Trying To Create A Small User Register system using html and php. I am Trying to Save All The inputed username onto a json file. Here Is my code

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
<form action="reg.php" method="post">
  Username: <input type="text" name="username">
  Password: <input type="text" name="password">
  <input type="submit">

</form>


<?php

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

  try
  {
       //Get form data
       $formdata = array(
          'firstName'=> $_POST['username'],
       );

       //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";
   }





 ?>




  </body>
</html>

But it always says

Warning: array_push() expects parameter 1 to be array, null given in C:\\Users\\XooT\\PHP\\User_database\\reg.php on line 35

What Can I Do and What Is the Problem?? can Anyone Help me

The error means that the $arr_data in your array_push($arr_data, $formdata); is an empty string.

Maybe the path to your existing JSON file is wrong?

Check what is in the $jsondata variable by going print_r($jsondata)

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