【发布时间】:2017-10-22 20:56:14
【问题描述】:
我需要一些帮助来尝试序列化 html 中的隐藏元素,而不是通过 post 将值传递给 php。这是我的代码:
<form action = "index.php" method = "POST" >
Enter name: <input type ="text" name = "name"><br></br>
enter ID: <input type = "text" name = "id"><br></br>
<input type = "hidden"
id = "hiddenStrArr"
name "hiddenStrArr"
value = "<?php print base64_encode(serialize("$arrayVar"))?>">
<input type = "submit" name = "submitButton" value = "Submit">
</form>
<?php
$nameExists = FALSE;
$name = ($_POST['name']);
$id = ($_POST['id']);
$hiddenStrArr = $_POST["hiddenStrArr"];
$arrayVar = unserialize(base64_decode($hiddenArray));
我的 php 中有一个 foreach 循环中的数组,它将检查来自用户的输入以及我的数组中的数据。问题是我的数组保持不变。如果我再次发布,它将重新从旧数组开始,但我希望它能够随着用户输入而更新。我正在尝试遵循本指南Passing Array Variables using POST or GET with PHP,但我不太了解。有人请帮助我或解释这是如何工作的。我收到一条错误消息,说 $name $id $hiddenStrArr 和 $arrayVar 是未定义的索引。谢谢你。
这里有更多代码可以帮助解释发生了什么:
<?php
$myTwoDimArr = array(1 => array("name1", 0, "123"),
2 => array("name2", 123, "456"),
3 => array("name3", 456, "789"),
4 => array("name3", 789, "101112"));
?>
<form action = "index.php" method = "POST" >
Enter name: <input type ="text" name = "name"><br></br>
enter ID: <input type = "text" name = "id"><br></br>
<input type = "hidden"
id = "hiddenStrArr"
name "hiddenStrArr"
value = "<?php print base64_encode(serialize("$arrayVar"))?>">
<input type = "submit" name = "submitButton" value = "Submit">
</form>
<?php
$nameExists = FALSE;
$name = ($_POST['name']);
$id = ($_POST['id']);
$hiddenStrArr = $_POST["hiddenStrArr"];
$arrayVar = unserialize(base64_decode($hiddenArray));
//this will check values from the html form against
//the values stored in the array than add 5 to $value[1]
foreach($myTwoDimArr as $key => $value){
if($key == $id && $value[0] == $name){
$myTwoDimArr[$key][1] = $myTwoDimArr[$key][1] + 5;
$nameExists = TRUE;
}
} //if values don't exist this creates a new element
//in the declared array
if ($nameExists === FALSE){
$newData = array($name, 1, date("Y-m-d"));
$myTwoDimArr[$id] = $newData;
}
//this will print values from the array
//the values are not being saved, I was hoping to use
//hidden element to accomplish this so that user may input
//more new values or add to existing values
foreach($myTwoDimArr as $key => $value){
echo "<tr><td>".$key."</td>
<td>".htmlspecialchars($value[0])."</td>
<td>".htmlspecialchars($value[1])."</td>
<td>".htmlspecialchars($value[2])."</td></tr>";
}
?>
【问题讨论】:
-
如果您有任何其他方式来传递此数据,请执行此操作。将其粘贴在表单中是要求某人对其进行篡改。
-
在你的代码的最后一行你正在反序列化 $hiddenArray,它没有出现在你的代码示例的其他地方 - 它不应该是 $hiddenStrArr 吗?
-
@tadman 没关系,这是我正在尝试为经验/教育做的家庭项目。除非我妻子学会了,否则没有人会篡改它:P
-
如果您正在学习,那很好,但这也意味着您应该以一种不那么古怪和复杂的方式来学习它,以至于它可以应用于现实世界的情况。
-
@lovelace 不确定您的意思,请进一步说明