【问题标题】:How to write to textfile from checkboxes?如何从复选框写入文本文件?
【发布时间】:2015-11-26 22:55:04
【问题描述】:

我在写入文本文件时遇到问题。用户在表单中的一个或多个复选框中单击的值。完成后,它应该将其打印到文本文件中。因此,如果用户标记肉类和苹果,它应该将其打印到文本文件 shoppingcart.txt 中。

我对 html、css 和 php 非常陌生。该代码低于我目前所取得的成果。

<article class="article">

<p>What in the store and their prices</p>

<?php


foreach($file as $line) {
echo $line;
}

?>

<p> Below you can order some things!</p>


<form method="post" action="">

<input type="checkbox" name="cb" value="meat"<br>
<input type="checkbox" name="cb" value="apple"<br>
<input type="checkbox" name="cb" value="drinks"<br>
<input type="submit" value="Submit">


<?php
$myfile = fopen("shoppingcart.txt", "w") or die("Unable to open file");

fwrite($myfile

?>
</form>

我应该在表格下方的 php 部分写什么?

【问题讨论】:

标签: php html


【解决方案1】:

index.html:

<form method="post" action="index.php">
            <input type="hidden" name="id" value="123" >
     Meat:  <input type="checkbox" name="cb[]" value="meat"><br/> // name is cb[] , not cb
     Apple: <input type="checkbox" name="cb[]" value="apple"><br/>
     Drinks:<input type="checkbox" name="cb[]" value="drinks"><br/>
            <input type="submit" value="Submit">
</form>

index.php:

<?php
$cb_v = isset($_POST['cb']) ? implode(',', $_POST['cb']) . PHP_EOL : '';
$id = isset($_POST['id']) ? $_POST['id'] : '';

 if ($cb_v && $id) {
    file_put_contents("/tmp/shoppingcart{$id}.txt", $cb_v, FILE_APPEND | LOCK_EX);
 }

【讨论】:

    【解决方案2】:

    这是一个非常基本的工作示例。您可以使用它作为开始添加更多有趣的功能:)

    <article class="article">
    
        <p>What in the store and their prices</p>
    
        <?php
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $result_string = '';
                foreach($_POST as $item) {
                    $result_string .= $item."\n";
                }            
                file_put_contents('shoppingcart.txt', $result_string , FILE_APPEND | LOCK_EX);
            }
        ?>
    
        <p> Below you can order some things!</p>
    
        <form method="post" action="">
            <input type="checkbox" name="meat" value="meat"<br>
            <input type="checkbox" name="apple" value="apple"<br>
            <input type="checkbox" name="drinks" value="drinks"<br>
            <input type="submit" value="Submit">
        </form>
    </article>
    

    【讨论】:

    • 最好也锁定文件; LOCK_EX。使用这种方法也无法区分一个用户的订单。
    • 谢谢你,jumanji。它有效,我唯一注意到的是,如果我选择苹果并且只喝其中一个附加在文本文件中。不知道为什么,但是以ty为例! :)
    • Ty chris85,我会宣传 LOCK_EX。
    • @IamnoobatSQL 如果我选择苹果和饮料似乎工作正常