从PHP表单提交选中的选项

时间:2014-02-14 00:57:19

标签: php html forms checkbox syntax-error

我正在试图找出如何将一系列复选框中的选中选项发送到跟踪所选内容的文本文件。我现在拥有的最多就是这个。

<html>
<?php
//Get contents from zmzonSongs.txt file, put into array.
$songList = explode("\n", file_get_contents('zmzonSongs.txt'));

print "Welcome to Zmzon.  Select songs below to add to your library.";
//Print contents as checklist.
foreach($songList as $songs){
    echo "<br/><input type='checkbox' name='songList[]' value='$songs' />"$songs<br>";
}

?>

</html>

我需要在用户点击提交按钮后将已检查的所有内容的值发送到myLibrary.txt等文件,但每次我尝试使用echo命令添加提交按钮时,我的整个页面都会停止工作,空白。我完全迷失了。

3 个答案:

答案 0 :(得分:1)

您的复选框和提交按钮应位于表单内,而您的提交按钮是HTML,而不是PHP。

<?php 
    /* Lets set the destination to the same file as the form. (see form action)
     * That means, if someone has submitted the form, there will be data inside 
     * $_POST right now! 
     */
    // var_dump( $_POST );  <-- Can be used to quickly peek inside $_POST

    if ( !empty( $_POST ) )  // Check if there is any data
    {
       save_data_to_file( $_POST ); // pseudo-code (should be replaced by you) 
       echo "success!";  // A success message perhaps?
       exit();  // Stop here to not display the form below.
    }

    // If we come this far, it means the form has not been submitted. 
    // So lets display the form!

    // You can have this line first in the file, or later, 
    // as long as you do this before you try to use it in your checkboxes.
    $songList = explode("\n", file_get_contents('zmzonSongs.txt'));
?>

<h1>Welcome to Zmzon.  Select songs below to add to your library</h1>
<form action="thisfile.php" method="POST"> 
    <?php 
        // See, you can jump between PHP and HTML whenever you want.
        foreach($songList as $songs){ 
            echo "<input type='checkbox' ... ><br>";
        }
    ?>
    <input type="submit">
</form>

您可以将数据发送到另一个页面或同一页面,由“操作”决定。 数据将在变量$ _POST或$ _GET内(取决于您选择的发送方法。)

查看这些全局变量的简单方法是使用var_dump()。例如:

<pre>
<?php var_dump($_POST); ?>

再次更新

答案 1 :(得分:0)

你有一个额外的引用:

echo "<br/><input type='checkbox' name='songList[]' value='$songs' />"$songs<br>";

应该是

echo "<br/><input type='checkbox' name='songList[]' value='$songs' />$songs<br>";

echo "<br/><input type='checkbox' name='songList[]' value='$songs' />".$songs."<br>";

答案 2 :(得分:0)

<html>
<form method='post'>
<?php
//Get contents from zmzonSongs.txt file, put into array.
if (!isset ($_POST['songList']))
{
   $songList = explode("\n", file_get_contents('zmzonSongs.txt'));
  print "Welcome to Zmzon.  Select songs below to add to your library.";
  //Print contents as checklist.
  foreach($songList as $songs){
      echo "<br/><input type='checkbox' name='songList[]' value='$songs' />"$songs<br>";
    }
}
else
{
 $songlist = $_POST['songList']; // which is array
// next you write code to update in text file.

}

?>
<input type="Submit" value="Submit">

</form>
</html>