doufan1899 2015-02-17 02:09 采纳率: 100%
浏览 101
已采纳

使用表单和PHP读取和修改存储在单独文件中的值

I'm new to PHP so excuse me in advance! I have done the following code to show two different buttons depending on if $status in the file vars.php is set 1 or 0 using . So far so good.

The problem: I now trying to make a very simple page with two option fields to set the $status in the vars.php. I want the script to read what the value of $status is and pres-select the corresponding option box, and have a submit button that saved either 1 or 0 to $status.

It sounds so simple, but I can't get this it to work.. I don't want to use a database, the file can be txt, xml or whatever. Please anyone help me!

Below is the IF script that just checks for the status value 1 or else.

<?php include 'vars.php'; ?>
<?php if ($status == "1") { ?>
<a class="button" href="pageA.php">Read more</a>
<?php } else { ?>
<a class="button" href="pageB.php">Read more</a>
<?php } ?>

What I'm trying to create is a tiny form with two options where I can swap the $status value between 1 and 0 (with the form option being pre-selected with whatever value $status has). When I press update it should overwrite the $status value in the vars.php.

  • 写回答

1条回答 默认 最新

  • dow56114 2015-02-17 02:31
    关注

    I would use JSON.

    vars.json:

    {
        "status": 1
    }
    

    then on your PHP:

    <?php
    $json = json_decode(file_get_contents("vars.json"));
    $href = ($json->status) ? "pageA.php" : "pageB.php";
    ?>
    <a class="button" href="<?= $href ?>">Read more</a>
    

    UPDATE: if you want to have a form set these variables without you having to manually modify the JSON data, then create another file, call it anything you want, we'll say form.php and place this inside:

     <?php
     $json = json_decode(file_get_contents("vars.json"));
     if (isset($_POST['status'])) {
        $json->status = (int)$_POST['status'];
        file_put_contents('vars.json', json_encode($json));
     }
     ?>
     <form method="post">
         <label>Status</label>
         <select name="status">
            <option value="1" <?= ($json->status) ? "selected" : "" ?>>TRUE</option>
            <option value="0" <?= (!$json->status) ? "selected" : "" ?>>FALSE</option>
         </select>
         <input type="submit"/>
     </form>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk