将组合框中的选定值存储到数据库中

时间:2014-09-17 16:47:42

标签: php html mysql

我试图创建一个带有文本输入的表单和一个加载了从数据库中检索的值和数据的组合框。我们的想法是,当您提交表单时,文本字段中的值将存储在数据库的某个字段中。我需要做的是将组合框的选定值(数字并从数据库的其他表中提取)(不是组合中显示的文本)存储到将存储表单文本字段的同一个表中

数据库结构由两个名为countries和appellations的表组成。国家/地区有一个名为country_id的字段和另一个名为country_name的字段(这两个字段填充组合框。表名称有三个名为appellation_id(pk,nn,ai),country_id和appellation_name的字段.sosllation_name字段必须填写在表单的文本字段,country_id必须填充组合框的选定值,该值等于countries表的country_id值。 到目前为止,我已经能够创建表单并使用db值加载组合框中的所有国家/地区。

表单代码是

<form name="New Appellation" action="actions/register_appellation.php" method="POST"     onsubmit="return validate()">
Nombre denominacion de origen:
<input type="text" placeholder="Nombre DO" name="fappellation_name">
<br>
Pais denominacion de origen:
<?php
include_once 'includes/fast_conn.php';
mysqli_select_db($cn,$db_name) or die(mysql_error());
$sql = "SELECT country_name, country_id FROM countries";
$rs = mysqli_query($cn,$sql) or die(mysql_error());
echo "<select name='appellation_country'>";
while($row = mysqli_fetch_array($rs)){
echo "<option value='".$row["country_id"]."'>".$row["country_name"]."</option>";
}mysqli_free_result($rs);
echo "</select>";
?>
<input type="submit" value="Registrar">

</form>

和处理POST register_appellation.php的php是:

<?php
include_once '../includes/fast_conn.php';
$fappellation_name=$_POST['fappellation_name'];
$fcountry_id=$_POST['country_id'];
$save="INSERT INTO $db_name($fcountry_id, $$fappellation_name)";
$result=mysqli_query($cn,$save);
if($result){
echo "<font size='+1' color='blue'> $fappellation_name, Successfully Registered.</font>";

}
else
{

echo "<font size='+1' color='red'>Registration Failed.</font>";

}
?>

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

我已经在下面包含了应该处理这个问题的修订源。

我在源代码中做了一些事情。我相信这一切都应该记录得相当好。以下列出了我添加的内容:

  1. 现在更新代码以完全使用MySQLi。
  2. 两种形式的MySQLi都是OOP风格(我偏爱MySQLi)。
  3. 有错误检查以确定事情是否成功并相应地显示错误。
  4. register_appellation.php现在检查字段是否已填写。
  5. register_appellation.php现在对查询变量执行卫生设施。 (有助于防止SQL注入攻击)
  6. register_appellation.php现在通过与countries表的交叉引用确认其收到的国家/地区ID有效。

  7. 这是表单代码:

    <form name="New Appellation" action="actions/register_appellation.php" method="POST"    onsubmit="return validate()">
    Nombre denominacion de origen:
    <input type="text" placeholder="Nombre DO" name="fappellation_name">
    <br>
    Pais denominacion de origen:
    <?php
    include_once 'includes/fast_conn.php';
    $boolSelectionSuccessful = $cn->select_db($db_name);
    if(!$boolSelectionSuccessful){
        $deathMessage = "<br><div>" .
            "Oh no! An error occurred on our end!<br>" .
            "Here's what we know:<hr>" .
            $cn->error .
            "<hr>" .
            "If this error continues to occur, please contact the website administrator." .
            "</div>";
        die($deathMessage);
    }
    $sql = "SELECT `country_name`, `country_id` FROM `countries`";
    $rs = $cn->query($sql);
    if($rs === FALSE){
        $deathMessage = "<br><div>" .
            "Oh no! An error occurred on our end!<br>" .
            "Here's what we know:<hr>" .
            $cn->error .
            "<hr>" .
            "If this error continues to occur, please contact the website administrator." .
            "</div>";
        die($deathMessage);
    }
    echo "<select name='appellation_country'>";
    while($row = $rs->fetch_assoc()){
        echo "<option value='".$row["country_id"]."'>".$row["country_name"]."</option>";
    }
    $rs->close();
    echo "</select>";
    ?>
    <input type="submit" value="Registrar">
    </form>
    

    这是register_appellation.php

    <?php
    include_once '../includes/fast_conn.php';
    
    function checkField($fieldName){
        if(isset($_POST[$fieldName])){
            if(!empty($_POST[$fieldName])){
                /* The request has the fieldName submitted && the fieldName was not left empty */
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    
    $checkArray = array(checkField('fappellation_name'), checkField('appellation_country'));
    if(in_array(false, $checkArray) || !is_numeric($_POST['appellation_country'])){
        /* the check assumes that 'appellation_country' (country id) should be numeric */
        die("<font size='+1' color='red'>Registration Failed. Please fill in all forms.</font>");
    }
    
    $boolSelectionSuccessful = $cn->select_db($db_name);
    if(!$boolSelectionSuccessful){
        $deathMessage = "<br><div>" .
            "Oh no! An error occurred on our end!<br>" .
            "Here's what we know:<hr>" .
            $cn->error .
            "<hr>" .
            "If this error continues to occur, please contact the website administrator." .
            "</div>";
        die($deathMessage);
    }
    $sql = "SELECT `country_name`, `country_id` FROM `countries`";
    $rs = $cn->query($sql);
    if($rs === FALSE){
        $deathMessage = "<br><div>" .
            "Oh no! An error occurred on our end!<br>" .
            "Here's what we know:<hr>" .
            $cn->error .
            "<hr>" .
            "If this error continues to occur, please contact the website administrator." .
            "</div>";
        die($deathMessage);
    }
    
    $countryIdValid = False;
    $countryName = "";
    /* $countryName is unused, by the current code, but it will still be set in the while loop.
       If you want to store the country name in the `appeallations` table, this variable
       could simply be added to the insert statement. */
    
    while($row = $rs->fetch_assoc()){
        if($row['country_id'] == $_POST['appellation_country']){
            $countryIdValid = true;
            $countryName = $row['country_name'];
            break;
        }
        /* else - continue looping to check the next country_id */
    }
    
    $rs->close();
    
    /* now that the loop has been exited, we'll make sure the country_id was verified */
    if(!$countryIdValid){
        die("<font size='+1' color='red'>Registration Failed. Unknown country.</font>");
    }
    
    $fappellation_name= $cn->real_escape_string($_POST['fappellation_name']);
    $fcountry_id = $cn->real_escape_string($_POST['appellation_country']);
    $save="INSERT INTO `appellations` (`country_id`, `appellation_name`) VALUES ('$fcountry_id', '$fappellation_name')";
    $result = $cn->query($save);
    if($result !== FALSE){
        echo "<font size='+1' color='blue'> " . $_POST['fappellation_name'] . ", Successfully Registered.</font>";
    }else{
        $deathMessage = "<br><div>" .
            "Oh no! An error occurred on our end!<br>" .
            "Here's what we know:<hr>" .
            $cn->error .
            "<hr>" .
            "If this error continues to occur, please contact the website administrator." .
            "</div>";
        die($deathMessage);
    }
    ?>
    

    如果我遗漏了任何内容,请随时编辑并更新我的答案。我没有运行代码,因此可能存在语法或逻辑错误,我没有注意到。

    希望这有帮助,

    斯潘塞