Felix Felix - 7 months ago 11
Javascript Question

how to insert data in database when I have two different names in my html for one column?

I know my title is a bit confusing so I'll explain it further on here. I know how to insert data in database, but I do not know how to do it when I have two different names in my HTML that should be inserted in my database.

I have a dropdown list for country, and the

select name
is
country1
. but when the user selects "Other" , a textbox will appear on the side that has a name
country2
and he should input his country. And I want that when he chooses "Other" and input his data, the data will insert in the database OR when he chooses from the dropdown list, it will do insert also.

When the user selects "Other", I want the data that he input in the textbox will be the one to be inserted in the database and not the word "Other", and when he selects from the list except "Other", I want the data that he selected will be the one to be inserted in the db.

Please please please do help me. If my question isn't clear enough please tell. Thank you.

My javascript code

function ValidateCountry(val){
var element=document.getElementById('country');
if(val==='Other')
element.style.display='block';
else
element.style.display='none';
}


HTML code

<form action="send.php" method="post">
<select name="country1" onchange='ValidateCountry(this.value);'>
<option> Select Country</option>
<option value="USA"> Lawyer </option>
<option value="Japan"> Nurse </option>
<option value="Other"> Other </option>
</select>
<input type="text" name="country2" id="country" style='display:none;'/>
<input type="submit" name="submit" />
</form>


And my PHP code:

include 'dbcontroller.php';

if(isset($_POST['submit']))
{
$country = $conn->real_escape_string(trim($_POST['country1']));
}
$query = "INSERT INTO info(occupation) VALUES ('$occupation')";
mysqli_query($conn,$query);

Answer

Very simply, use an if/else

if($_POST['country1'] == 'Other')
{
     $country = $_POST['country2'];
} else {
     $country = $_POST['country1'];
}

Or with one line:

$country = $_POST['country1'] == 'Other' ? $_POST['country2'] : $_POST['country1'];

Then you can use $country in your query.

Comments