如何从复选框写入文本文件?

时间:2015-11-26 14:19:01

标签: php html html5

写入文本文件时遇到问题。用户在表单中的一个或多个复选框中单击的值。完成后,它应该将其打印到文本文件。因此,如果用户标记肉和苹果,则应将其打印到textfile 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部分写什么?

2 个答案:

答案 0 :(得分:0)

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

<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>

答案 1 :(得分:0)

的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);
 }