I'm trying to create my first function in PHP, a drop down. It's almost working, but when I submit/post the data the options with a space in it will only show the first word in the output.
In the example I have 'First Name' as an option in the drop down list. When I hit submit, the output will only be 'First'. When I change 'First Name' to 'First-Name' it works, the output is 'First-Name'. So I think I need to add quotes somewhere in the code so that it is handled as a string??
Hope someone can help me out, I'm so close to what I want.
<!DOCTYPE HTML>
<html>
<body>
<?php
include('db_functions.php');
function clean_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fName = clean_input($_POST['first_name']);
}
//drop down function
function dropdown($name, $options) {
$dropdown = '<select type="text" name='.$name.'>'."
";
$rows = $options;
if($rows === false) {
$error = db_error();
}
$totalrows = count($rows);
for ($x = 0; $x < $totalrows; $x++) {
$dropdown .= '<option value=' . $rows[$x][$name] . '>' . $rows[$x][$name] . '</option>'."
";
}
$dropdown .='</select>'."
";
return $dropdown;
}
echo '<form action="' . htmlspecialchars($_SERVER["PHP_SELF"]) . '" method="post">';
//start dropdown
echo 'First Name:';
$name = 'first_name';
$options = db_select("SELECT DISTINCT first_name FROM nametable GROUP BY first_name ORDER BY first_name ASC LIMIT 20");
echo dropdown($name, $options);
//end dropdown
echo '<input type="submit" name="submit" value="Submit">';
echo '</form>';
echo $fName;
?>
</body>
</html>
Your code is writing
<option value=First Name>
The space ends the value, so Name
is a separate attribute. You need to put the value in quotes, so it's
<option value="First Name">
The code should be:
$dropdown .= '<option value="' . $rows[$x][$name] . '">' . $rows[$x][$name] . '</option>'."
";