简体   繁体   English

如何通过 html、json 和 php 中的输入帖子添加到列表?(不使用数据库)?

[英]How do i add to a list via an input Post in html, json, and php?(without using a database)?

I have been struggling with this for a while.我已经为此苦苦挣扎了一段时间。 I think there is a missing piece in my logic and I cannot figure out what it is.我认为我的逻辑中有一个缺失的部分,我无法弄清楚它是什么。 I am trying to make a todo app using Html, json and php.我正在尝试使用 Html、json 和 php 制作待办事项应用程序。 how do I make the input values store as an array and then echo out as a todo list?如何将输入值存储为数组,然后作为待办事项列表回显?

<form method="POST" action="TodoAppChallenge.php">
    <p>
        <label for="wordsGoHere">type your task here</label>
        <input type="text"  id ="wordsGoHere" name="wordsGoHere">
    </p>
    <input type="submit" name="pressHere" value="           add Your Task               ">
</form>
<?php
include('TodoAppChallengeExtra.php');
?>

<table>
      <thead>
      <th>Your Tasks</th>
      </thead>
      <tbody>
<?php
    if(isset($_POST['pressHere'])){
                  
            $wordsGoHere = array(
            'wordsGoHere' => $_POST['wordsGoHere'],
      );    //i think my mistake is somewhere around here
            array_push($wordsGoHere,$_POST['wordsGoHere']);
            $data = $wordsGoHere;
            $data = json_encode($data, JSON_PRETTY_PRINT);
            file_put_contents('extra.json', $data);
            $data = file_get_contents('extra.json');
            $data = json_decode($data);
            foreach($data as $row){
            echo "
                  <tr>
                        <td>
                        <ul><li>".$row->$data."</li></ul>
                        </td>
                  </tr>
            ";
    }} else {
      echo 'add a Task';
     }
      ?>
       </tbody>
 </table>

The code is commented but here are the main points:代码已注释,但要点如下:

  • Move form processing up top to avoid, "Headers already sent..." errors将表单处理上移以避免“标题已发送...”错误
  • turn on error reporting开启错误报告
  • Use sane, plain-language variable names使用理智的、通俗易懂的变量名
  • Keep your arrays as simple as you can让您的 arrays 尽可能简单

Other items you can do to improve?您还可以做些什么来改进? Use constants to define things like the session key todo , validation, split it up into a processing file and a presentation file.使用常量来定义诸如 session key todo ,验证之类的东西,将其拆分为处理文件和演示文件。

If you want to go a bit more advanced, design a storage mechanism where your form and form processing logic don't know or care about whether the data is stored in a JSON file, session, database, or something else.如果你想 go 更高级一点,设计一个存储机制,你的表单和表单处理逻辑不知道或不关心数据是否存储在 JSON 文件、Z21D6F40CFB511982E4424E0E250 或其他文件中。 It would look something like: $storage->save($userInput);它看起来像: $storage->save($userInput); and $storage->retrieve();$storage->retrieve();

Good luck!祝你好运!

Implemented via session.通过 session 实现。

<?php

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

// Always do these 2 things on every request.

// 1. Start your session
session_start();

// 2. Initialize the session array if it hasn't been initialized already.
// This only happens once per session.
if (!isset($_SESSION['todo'])) {
    $_SESSION['todo'] = [];
}

// Now you are free to start writing and reading from your session.

// Check if the request is coming in via POST.
// Do your processing up top above your HTML otherwise you can run into "Headers already sent..." errors.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // This is what the user typed in.
    $input = $_POST['wordsGoHere'];

    // @todo do your validation here.

    // Put the user's input in the session.
    $_SESSION['todo'][] = $input;
}

// Finally, read out the contents from your session so your form has access to it.
$dataFromSession = $_SESSION['todo'];
?>

<form method="POST">
    <p>
        <label for="wordsGoHere">type your task here</label>
        <input type="text" id="wordsGoHere" name="wordsGoHere">
    </p>

    <input type="submit" name="submit" value="Add Your Task">
</form>
<table>
    <thead>
    <tr>
        <th>
            Your Tasks
        </th>
    </tr>
    </thead>

    <tbody>
    <?php foreach ($dataFromSession as $item): ?>

        <tr>
            <td>
                <?= $item; ?>
            </td>
        </tr>

    <? endforeach; ?>
    </tbody>
</table>

Implemented via JSON file.通过 JSON 文件实现。

<?php

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

// Initialize your JSON file by ensuring the file actually exists. If it doesn't, create an empty file.
if (!file_exists('extra.json')) {
    file_put_contents('extra.json', '[]');
}

// Now you are free to start writing and reading from your JSON file.

// Check if the request is coming in via POST.
// Do your processing up top above your HTML otherwise you can run into "Headers already sent..." errors.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // This is what the user typed in.
    $input = $_POST['wordsGoHere'];

    // @todo do your validation here.

    // Read the current state of the file.
    $contents = file_get_contents('extra.json');
    $dataFromFile = json_decode($contents, true);

    // Push the new value on the end of the array.
    $dataFromFile[] = $input;

    // Write the array back to the file.
    $json = json_encode($dataFromFile, JSON_PRETTY_PRINT);
    file_put_contents('extra.json', $json);
}

// Finally, read out the latest contents from your file so your form has access to it.
$contents = file_get_contents('extra.json');
$dataFromFile = json_decode($contents, true);
?>

<form method="POST">
    <p>
        <label for="wordsGoHere">type your task here</label>
        <input type="text" id="wordsGoHere" name="wordsGoHere">
    </p>

    <input type="submit" name="submit" value="Add Your Task">
</form>
<table>
    <thead>
    <tr>
        <th>
            Your Tasks
        </th>
    </tr>
    </thead>

    <tbody>
    <?php foreach ($dataFromFile as $item): ?>

        <tr>
            <td>
                <?= $item; ?>
            </td>
        </tr>

    <? endforeach; ?>
    </tbody>
</table>

I've tried to make this simpler, you have lots of variable re-assignment which you don't need.我试图让这更简单,你有很多你不需要的变量重新分配。 Basically基本上

  if(isset($_POST['pressHere'])){
   // get the tasks, note the 'true' flag on the json decode so you have an array rather than an object

    $tasks = json_decode(file_get_contents('extra.json'), true);
    
    //keep things simple - use the same array and just add the new value to it

    $tasks[] = $_POST['wordsGoHere'];

    //print out your values
    foreach($tasks as $task){
        echo "
              <tr>
                    <td>
                    <ul><li>" . $task . "</li></ul>
                    </td>
              </tr>
        ";
    }

    //using the same array prepare to save it
    $tasks = json_encode($tasks, JSON_PRETTY_PRINT);

    //save the data
    file_put_contents('extra.json', $tasks);


} else {
    echo 'add a Task';

}

it's much simpler to read, easy to follow, makes sense and (importantly) works它更易于阅读,易于理解,有意义并且(重要)有效

//EDIT It's worth saying, i've just followed your logic here so the list only shows when you post it, if you want it to show all the time you'd just need to slightly change the logic like this: //EDIT 值得一说,我只是按照你的逻辑在这里,所以列表只在你发布它时显示,如果你希望它一直显示你只需要稍微改变这样的逻辑:

$tasks = json_decode(file_get_contents('extra.json'), true);

if(isset($_POST['pressHere'])) {
    $tasks[] = $_POST['wordsGoHere'];
}

if(count($tasks) > 0) {
    foreach($tasks ....
    ....
} else {
    echo 'add a Task';

}

暂无
暂无

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

相关问题 如何使用受控语句和html表单通过php通过php向mysql db添加一行到用户输入? - How do I add a row to mysql db via php using controlled statements and html form for user input? 如何在不透露答案的情况下确定 HTML 格式的答案是否正确(通过 $.post 调用 PHP)? - How do I determine if a HTML-form answer is correct (calling PHP via $.post), without revealing the answer? 如何使用 html 输入字段从 php 代码显示 javascript 数组中的列表? - How do i show a list in a javascript array from a php code using a html input field? 如何在不使用PHP的文件处理功能的情况下通过PHP将HTTP内容中的二进制内容上传到MYSQL数据库中? - How do I upload binary content from an HTTP post into a MYSQL database through PHP without using PHP's file handling functions? 在PHP中使用“ POST”在C#中通过JSON检索数据库信息 - Using 'POST' in PHP to retrieve database information via JSON in C# 如何使用PHP将JSON有效负载发布到Web服务? - How do I post JSON payloads to a web service using PHP? 如何在没有 PHP 输入标签的情况下通过 POST 将值发送到其他页面 - how can i send a value to other page via POST without Input Tag in PHP 如何在不使用ajax的情况下将数据从一个php文件发布到另一个php文件以将数据添加到数据库 - How to post data from a php file to another php file to add the data to database without using ajax 如何基于用户输入从数据库中获取数据并使用PHP中的异步POST显示为JSON数组 - How to fetch data from database based on user input and display as JSON array using asynchronous POST in php 如何通过jQuery Ajax发布数据在PHP中编码JSON? - How do I encode JSON in PHP via jQuery Ajax post data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM