从下拉列表中携带值到数据库

时间:2015-03-11 07:44:05

标签: php mysql sql mysqli

我的html表单中有一个下拉列表,我需要在数据库中插入值。表格就像这样

<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> 

表单的后端,即add_country.php,包含以下代码,

$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;
        }
    } 

但是我无法使用countryname获取countryid(没有显示任何内容)。为了测试目的,当我试图回显国家名称时,我输出为

africa\r\n

也许因为它,我无法匹配数据,但我不太确定。任何人都可以告诉我如何获取值

2 个答案:

答案 0 :(得分:0)

<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> 

您可以直接在value属性中使用id,因此无需再次从表中获取id。

答案 1 :(得分:0)

使用 Trim() 功能

 $countryname =trim($_POST['countryname']);
      $country_name mysqli_real_escape_string($con,$countryname);
    echo $country_name;