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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动