我想通过单击按钮将用户输入从文本框存储到外部 php 数组中。此外,还有两个单选按钮的依赖性。
这是我当前的尝试:
首先,我包含外部 php 数组:
<?php
include ('../array.php');
?>
输入形式:
<form action="" method="post">
<input type="text" name="textfield" id="txt1" value="">
<input type="radio" name="name" id="id" value="Type1">Type1<br>
<input type="radio" name="name" id="id" value="Type2">Type2<br>
<button id="submit" name="send" type="submit">Save</button>
</from>
将值插入数组:
<?php
if (isset($_POST['send'])){
if (isset ($_POST['name'])){
if ($_POST['name']=='Type1'){
$newword = $_POST['textfield'];
$array[] = $newword;
}
}
}
?>
但是这些值不会“堆叠”,这意味着数组不会随着每次单击按钮而增长。 有人可以帮忙吗? :D
提前致谢!
最佳答案
如果你想堆叠值,你需要将它们存储在某个地方,以便在每个对服务器的请求之间保存值。
值可以存储在 session 中(仅适用于当前用户)或 PHP 支持的任何数据库中。
这是一个 session 示例:
index.php:
<?php
include ('./array.php');
?>
<form action="" method="post">
<input type="text" name="textfield" value="">
<input type="radio" name="name" value="Type1">Type1<br>
<input type="radio" name="name" value="Type2">Type2<br>
<button id="submit" name="send" type="submit">Save</button>
</from>
数组.php:
<?php
session_start();
if (!is_array($_SESSION['persistentValues'])) {
$_SESSION['persistentValues'] = array();
}
if (isset($_POST['send']) && isset($_POST['name']) && $_POST['name']=='Type1') {
$_SESSION['persistentValues'][] = $_POST['textfield'];
}
print_r($_SESSION['persistentValues']);
?>
关于PHP - 将输入值存储在外部 php 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53299018/