gpt4 book ai didi

PHP 过早更新表

转载 作者:太空宇宙 更新时间:2023-11-04 14:25:53 25 4
gpt4 key购买 nike

我有这个程序,用户可以在其中输入消息和表单中的名称。然后程序将这些信息保存在一个 json 文件中。然后将 json 文件中的条目输出到表中。

除了在表中添加新条目时,一切都按我希望的方式进行。当我单击提交按钮时,表格会更新为一个空条目。如果我随后更新页面,该表将输入正确的值。

我查看了保存 json 对象的文件,表单数据已正确发送。从我的角度来看,表格似乎在获取程序读取新条目之前得到了更新。但是,我真的不明白为什么,因为 foreach 循环遍历的是本地数组 $tempArray 并且在执行提交时该数组会更新为新条目。

<?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>

最佳答案

JavaScript 没有关联数组。因此,此类 PHP 数组被转换为对象。您正在从 JSON 文件中读取对象,但附加了一个关联数组。

除了最新添加的数组外,在循环中一切正常。 $obj->name 无法访问数组元素 $obj['name']

通过将代码更改为来处理对象

$new_post = (object)[
'name' => $name,
'text' => $text,
'date' => $date,
'ip' => $_SERVER['REMOTE_ADDR'],
];

关于PHP 过早更新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54497345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com