Reputation: 3
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
Upvotes: 0
Views: 512
Reputation: 330
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)
Upvotes: 1