i have a dropdown in my html form through which i need to insert values in the database. the form is like this
<form action="add_country.php" method="post">
<label>Category</label>
<select name="countryname">
<?php
require 'connection.php';
$sql = "SELECT * FROM country";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result))
{
$countryname=$row["countryname"];
?>
<option value="<? echo $countryname;?>"><? echo $countryname;?></option>
<?}
}?>
</select>
</form>
the back end of the form i.e add_country.php ontains the following code,
$countryname = mysqli_real_escape_string($con, $_POST['countryname']);
echo $countryname;
$sql = "SELECT * FROM country where countryname='".$countryname."'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$countryid=$row["id"];
echo $countryid;
}
}
but i am not able to fetch the countryid using the countryname (nothing gets displayed). for testing purpose when i tried to echo the countryname i got output as
africa
maybe coz of it, i am not able to match the data, however i am not so sure. can anyone tell how i can fetch the value
<form action="add_country.php" method="post">
<label>Category</label>
<select name="countryname">
<?php
require 'connection.php';
$sql = "SELECT * FROM country";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result))
{
$countryname=$row["countryname"];
$countryid = $row["id"];
?>
<option value="<? echo $countryid;?>"><? echo $countryname;?></option>
<?}
}?>
</select>
</form>
You Can Use directly id in value attribute so no need to fetch id again from table.
Use Trim() function
$countryname =trim($_POST['countryname']); $country_name mysqli_real_escape_string($con,$countryname); echo $country_name;