I have this program where a user inputs a message and name in a form. Then the program saves this information in a json file. The entries in the json file are then output in a table.
Everything works as I want it to except for when I add a new entry in the table. When I click the submit button the table gets updated with an empty entry. If I then update the page the table gets input with the right values.
I've looked at the file the json objects are saved to and the form data is sent correctly. From my point of view it seems like the table gets updated before get program reads the new entry. However, I don't really understand why since it's the local array $tempArray
that the foreach loops through and this array gets updated with the new entry when the submit is performed.
<?php
//open & read php file
$json = file_get_contents("../../../writeable/test2.json");
$tempArray = json_decode($json);
//get form values
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$text = $_POST['text'];
$date = date("m-d-Y h:i", time());
//create new json object
$new_post = array(
'name' => $name,
'text' => $text,
'date' => $date,
'ip' => $_SERVER['REMOTE_ADDR']
);
//add new json object to array
$tempArray[] = $new_post;
print_r($tempArray);
}
//encode array into json & save to file
$my_json = json_encode($tempArray);
$fh = fopen("../../../writeable/test2.json", 'wd') or die("can't open file");
fwrite($fh, $my_json);
fclose($fh);
?>
<!DOCTYPE html>
<html lang="sv-SE">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css"/>
<title>DT161G-Laboration1</title>
</head>
<body>
<table id="guestbook">
<?php
foreach ($tempArray as $obj) { //loop through array with posts
echo '<tr>';
echo '<td>' . $obj->name . '</td>';
echo '<td>' . $obj->text . '</td>';
echo '<td>' . 'IP: ' . $obj->ip . '</br>TID: ' . $obj->date . '</td>';
echo '</tr>';
}
?>
</table>
<form action="guestbook.php" method="POST">
<input type="text" placeholder="Write your name"
name="name">
<br>
<label for="text">Your message</label>
<textarea id="text" name="text"
rows="10" cols="50"
placeholder="Message .."></textarea>
<br>
<button type="submit" name ="submit">Send</button>
</form>
</body>