将确切的数据值插入数据库

时间:2016-04-07 15:51:44

标签: php mysql

我需要帮助。我有这个代码并且它按照我的意愿工作但是当插入数据库时​​,它插入了id和我用作主键和外键的state_id来创建两个表之间的关系。数据库。我希望它插入精确的值而不是id或state_id。感谢。

<?php
 include 'dbconnect.php';
 $query = "SELECT `id`,`states` FROM `states`";
 $result1 = mysqli_query($dbconnect,$query);
 $rows = mysqli_num_rows($result1);
 if ($rows){
   while($row = mysqli_fetch_assoc($result1)){
   $states[] = array("id" => $row['id'], "val" => $row['states']);
 }
}

 $query = "SELECT `id`, `state_id`, `local_government` FROM `local_governments`";
 $result2 = mysqli_query($dbconnect,$query);
 $rows2 = mysqli_num_rows($result1);
 if ($rows2){
   while($row2 = mysqli_fetch_assoc($result2)){
   $local_government[$row2['state_id']][] = array("id" => $row2['id'], "val" => $row2['local_government']);
  }

   $jsonStates = json_encode($states);
   $jsonLocal_government = json_encode($local_government);
}

 if (isset($_POST['submit'])){
     $stateOforigin = htmlspecialchars(trim($_POST['stateOforigin']));
     $LGA = htmlspecialchars(trim($_POST['LGA']));

     $sql = "UPDATE `sono` SET `stateOforigin`='$stateOforigin', `LGA`='$LGA' WHERE `eMail`='$email'";
     $check = mysqli_query($dbconnect, $sql);
     header ('location: form2.php');        
    ?>



    <script type="text/javascript">
    <?php
      echo "var states = $jsonStates; \n";
      echo "var local_government = $jsonLocal_government; \n";
  ?>
     function loadStates(){
      var select = document.getElementById("statesSelect");
      select.onchange = updateLocal_government;
      for(var i = 0; i < states.length; i++){
      select.options[i] = new Option(states[i].val,states[i].id);          
     }
   }
     function updateLocal_government(){
      var statesSelect = this;
      var state_id = this.value;
      var local_governmentSelect=document.getElementById("local_governmentSelect");
  local_governmentSelect.options.length = 0; //delete all options if  any present
      for(var i = 0; i < local_government[state_id].length; i++){
      local_governmentSelect.options[i] = new Option(local_government[state_id][i].val,local_government[state_id][i].id);
      }
   }

 </script>
   <body onload='loadStates()'>
   <p style='padding-left: 0px; font-size: 12px; font-weight: bold'>State Of Origin</p>
        <p><select name="stateOforigin" class="userarea" id="statesSelect"></p></select>
        <p style='padding-left: 0px; font-size: 12px; font-weight: bold'>Local Govt. Area</p>
        <p><select name="LGA" class="userarea" id="local_governmentSelect">
        <option value="Null">Loading</option></p>
        </select>
</body>

1 个答案:

答案 0 :(得分:0)

现在你正在使用 new Option(states[i].val,states[i].id) 这导致了 <option value = states[i].id>states[i].val</option>

当您提交form时,valueoption的{​​{1}}用于$_POST,而不是<option></option>标记之间的文字。该文本仅适用于我们人类,因此我们了解我们正在选择的内容。

将命令更改为 new Option(states[i].val,states[i].val) 会导致 <option value = states[i].val>states[i].val</option> 现在,$_POST中使用了所需的值。

从标准化的角度来看,@ CBroe所说的也是如此,但也许不是你想要的。