Satish
Satish

Reputation: 17397

php read file and create drop down menu

I have following php code which create Drop-Down menu reading text file which contain name

files.txt

JAMES
MARK
TONY

drop-down.php

<?php
$path = "files.txt";
$file = fopen($path, 'r');
$data = fread($file, filesize($path));
fclose($file);

$lines =  explode(PHP_EOL,$data);
echo '<select name="file">';
foreach($lines as $line) {
  echo '<option value="'. urlencode($line).'">'.$line.'</option>';
}
echo '</select>';
?>

Here is the POST section of code, it is a loop

foreach ($_POST["bname"] AS $id => $value)
{
...
...   
USERNAME: "'.$_POST["file"][$id].'"

Everything working but when i submit data to other form i am getting only first letter of users like if i select JAMES and submit data i am only getting J letter in .$_POST. I want Full name JAMES, what is wrong in my code?

Upvotes: 0

Views: 5557

Answers (3)

CoursesWeb
CoursesWeb

Reputation: 4237

Try read the txt file with file(), it adds the rows directy into an array, then use for() to traverse the array.

<?php
$path = "files.txt";
$lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nrl = count($lines);
echo '<select name="file[]">';
for($i=0; $i<$nrl; $i++) {
  echo '<option value="'. urlencode($lines[$i]).'">'.$lines[$i].'</option>';
}
echo '</select>';

Upvotes: 1

Get Off My Lawn
Get Off My Lawn

Reputation: 36299

You don't need the Id, because that is saying "I want this value, and the second part says which character" (at least the way that you are using it). Try this:

"USERNAME " . $_POST["file"]

Strings are treated like arrays in PHP.

So if you had the string kitty

$string = "Kitty";
echo $string[0]; // prints "K"
echo $string[4]; // prints "y"

Upvotes: 1

Marcelo Pascual
Marcelo Pascual

Reputation: 820

The name attribute of your select is wrong, must be:

echo '<select name="file[]">';

or

echo '<select name="file[someNumber]">';

Upvotes: 1

Related Questions