【问题标题】:PHP - Store input values in external php arrayPHP - 将输入值存储在外部 php 数组中
【发布时间】:2018-11-14 11:19:54
【问题描述】:

我想通过单击按钮将文本框中的用户输入存储到外部 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

提前致谢!

【问题讨论】:

  • 你不能有超过 1 个元素的相同 id... -> 2 x id="id"
  • '他们不“堆叠”'是什么意思?你能提供一个实际的和预期的结果吗?
  • with stack 我的意思是,发送到数组的项目不会累积堆叠。就像第一个按钮点击数组是('1'),第二个按钮点击它的('1','2')等等。
  • 删除那些重复的 id 属性...使用不同的 id 或使用 class="whatever" 如果你 print_r($array);在你的脚本的末尾?哦,修复那些嵌套的条件(if 语句)......你可以在一个 if 中完成它们并使用 &&

标签: php arrays


【解决方案1】:

如果要堆叠值,则需要将它们存储在某个位置,以在对服务器的每个请求之间保留值。

值可以存储在会话中(仅限当前用户)或 PHP 支持的任何数据库中。

这里是一个会话示例:

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>

array.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']);

?>

【讨论】:

  • 是的,我认为将所有数组条目存储在数据库中是最简单的。
【解决方案2】:
<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 中放这个

<?php

  if (isset($_POST['send']) && $_POST['textfield'] && $_POST['name']){
       if ($_POST['name']=='Type1'){
           array = require('./array.php');
           $newword = $_POST['textfield'];
           $array[] = $newword;
       }
   }

 ?>

【讨论】:

  • 我收到这条消息:解析错误:语法错误,意外 '=',期待 '(' 关于“array = require...”的行
  • 很抱歉请添加 $array = require('../array.php');
  • $array = require('../array.php');... ??真的吗?
  • 请 require 文件 array.php ok 试试这个 require('./array.php')
猜你喜欢
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多