I get a strange problem when extracting the selected option of an html drop down list embedded in a php script, from another PHP script. If the words of the option values are separated with spaces. PHP echos only the first word of the selected option value. What I’m doing wrong here?
list.php
<body>
<form action="extract.php" method="post">
<?php
$one = "one one";
$two = "two two";
$three = "three three";
echo '<select name="selected_item">';
echo '<option value='.$one.'>'.$one.'</option>';
echo '<option value='.$two.'>'.$two.'</option>';
echo '<option value='.$three.'>'.$three.'</option>';
echo '</select>';
?>
<input type="submit" class="button" value="submit" name="submit" />
</form>
</body>
</html>
extract.php
<?php
if (isset($_POST['submit'])) {
$item_name = $_POST['selected_item'];
echo $item_name;
}else{
echo "item not selected";
}
?>
If I select “three three” in the list PHP echos only “three”. Why is that?
It’s because you didn’t quote your HTML attributes. When you have this code:
This will come out as HTML:
The PHP string quotes are gone in the output. And only the first
threewill become attribute value. The other will just be trailing garbage.You need a better echo:
Even better might be a HEREDOC string in such cases. And don’t forget
htmlspecialchars()for non-static content.