繁体   English   中英

通过表单提交更改 PHP 变量/值

[英]Change a PHP variable/value via form submit

我想更改我的 html 页面上的一些值,比如我的社区名称。 我输入值并单击提交按钮。 我希望那个小按钮根据我在表单上更改的内容来更改变量的值(如果这有意义的话)。

如果有帮助,我正在使用 Bootstrap(最新版本)。

配置文件

$communityName = "My Community";
$communityLinks = array("Home", "Store", "Forum");

功能.php

if (isset($_POST['communityName'])) {
   $communityName = ($_POST['communityName']);
}
if (isset($_POST['communityLinks'])) {
   $communityLinks = str_replace("\r\n", '","',($_POST['communityLinks']));
}

索引.php

<?php
include ("config.php");
include ("functionality.php");
?>
<div id="accordion" class="container">
    <div class="card b-light-shadow">
        <div class="card-header" id="headingOne">
            <h5 class="mb-0">
                <button class="accord-btn btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                Basics
                </button>
            </h5>
        </div>
        <div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordion">
            <div class="card-body">
                <form action="" method="post">
                    <div class="form-group">
                        <label for="exampleFormControlTextarea1">Community Name</label>
                        <input class="form-control" id="exampleFormControlTextarea1" rows="1" name="communityName" placeholder="Community Name" value="<?= $communityName ?>">
                    </div>
                    <div class="form-group">
                        <label for="exampleFormControlTextarea1">Community Lins</label>
                        <p class="form-description">Change your links here.</p>
                        <textarea class="form-control" rows="3" name="communityLinks" type="text"><?php $i = 0; $len = count($communityLinks); foreach ($communityLinks as $cL) { echo $cL; if ($i != $len - 1) { echo "&#013;"; } $i++;  } ?></textarea>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="row" style="margin-top: 3em;">
        <div class="container">
           <button class="subm-btn btn btn-link" type="submit" name="action">Save</button>
        </div>
    </div>
</div>

我在这里做错了什么?

将您的提交按钮放在表单中。 现在它什么也没做。

看起来你很接近。 但是,您没有使用$communityName显示在您的 HTML 代码中。

要做到这一点,只需替换这个:

<label for="exampleFormControlTextarea1">Community Name</label>

有了这个:

<label for="exampleFormControlTextarea1"><?= $communityName ?></label>

现在,如果您成功发布到此页面,名称应该会更改。

接下来,正如@user3783243 提到的那样。 str_replace会给你一个字符串,但你使用$communityLinks作为一个数组,所以你需要一个链接数组。 您应该使用explode()函数从您的用户输入中获取一个数组。

这样的事情可以工作:

$communityLinks = explode("\r\n", $_POST['communityName']);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM