开发者

PHP and HTML Checkboxes using POST

开发者 https://www.devze.com 2023-02-13 18:31 出处:网络
I have a php file which lists all the files in a directory with checkboxes next to each one: <html <body>

I have a php file which lists all the files in a directory with checkboxes next to each one:

<html
<body>
<P>List of files:</p>

<form action="submitfiles.php" method="post">

<?php
 if ($handle = opendir('./files')) {

   while (false !== ($file = readdir($handle)))
   {
          if ($file != "." && $file != "..")
          {
            $thelist .= '<a href="'.'./files/'.$file.'">'.$file.'</a>';
 开发者_开发技巧           $thelist .= '<br>';

            $s = '<input type="checkbox" name="'.$file.'" value="yes"/><a href="'.'./files/'.$file.'">'.$file.'</a>';
            echo $s;
            echo '<br';
          }
   }
  closedir($handle);
  }
?>
</body>

<input type="submit" name="formSubmit" value="Submit"/>
</form>

</html>

Then, I have a submitfiles.php, which loops through all the files, and gets the $_POST values for each checkbox.

<?php


 if ($handle = opendir('./files')) {
   while (false !== ($file = readdir($handle)))
   {
          if ($file != "." && $file != "..")
          {

                echo 'Value is ' . $_POST['$file'] . '<br>';
                echo $file . '<br>';

          }
   }
  closedir($handle);
  }

?>

Even if I check a checkbox though, the line "Value is " in my php file always prints a blank. Meaning, none of the checkboxes are ever given a value. How do I get this working? If I checked a checkbox, I want it to print "Value is yes", but it doesn't.


Okay - there is a slight disconnect in your code...

Here is the checkbox:

<input type="checkbox" name="'.$file.'" value="yes"/>

Here is your attempt to get it:

$_POST['$file']

The name of the checkbox isn't "$file" - it is the value of the variable $file...

So try changing them to...

<input type="checkbox" name="file[]" value="yes"/>

And get them like this...

$FileCheckBoxes = $_POST['file'];

Now $FileCheckBoxes will contain a list of the ones that were checked.


You want to have checkboxes to output an array.

<input type="checkbox" name="assigned_name[]" value="1"> Item 1
<input type="checkbox" name="assigned_name[]" value="2"> Item 2


On the line

echo 'Value is ' . $_POST['$file'] . '<br>';

in submitfiles.php, try not using quotes around $file, like so:

echo 'Value is ' . $_POST[$file] . '<br>';

Using single quotes forces PHP to not evaluate the value of $file. Read up on single quotes at http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single


The problem is this line here:

echo 'Value is ' . $_POST['$file'] . '<br>';

Remove the single quotes around the array key (or use double quotes):

echo 'Value is ' . $_POST[$file] . '<br>';

When you use single quotes, the variable $file is being passed as a string. You can read more about why this is true here: http://php.net/string/

0

精彩评论

暂无评论...
验证码 换一张
取 消