My aim is to get the selected item from the drop down and covert it to type string. After conversion, am comparing the result with another string and then use if() statement to execute some code. But the conversion does not seem to work because the program only execute else() statement. How can I do this? somebody help Please.
Below is my html and php code.
<select name="p_category">
<option selected disabled >-- select --</option>
<option value="computers">Computer</option>
<option value="phones" >Phone</option>
<option value="accessories">Accessory</option>
<option value="general">Display</option>
</select>
<?php
$getCategory = $_POST['p_category'];
$value = strval($getCategory);
$comps = "computer";
if($value == $comps){
echo "<script>alert('Equal')</script>";
}else{
echo "<script>alert('Not equal')</script>";
}
?>
My Answer:
The issue in your code is that you are comparing the selected option value with "computer" instead of "computers". Also, you don't need to convert the selected option value to a string using strval() as it is already a string.
Here is the corrected code:
html
if(isset($_POST['p_category'])){
$getCategory = $_POST['p_category'];
$comps = "computers";
if($getCategory == $comps){
echo "";
}else{
echo "";
}
}
?>
In this code, I have corrected the comparison value to "computers" and removed the unnecessary conversion to a string. I have also added a check to see if the form has been submitted before trying to access the selected option value.
Rate this post
3 of 5 based on 1645 votesComments