如何将数据从JavaScript传递到PHP再到MySQL

时间:2016-02-08 23:45:34

标签: javascript php mysql post

我有一些麻烦要将JS变量传递给PHP变量然后传递给sql查询..看看代码:

以下val()方法显示组合框的选定值,并将js变量正确传递给php变量:

<script>
  function val() {
    player = document.getElementById("combo").value;
    document.getElementById("demo").innerHTML = "<?php $player_name = '"+player+"'; echo "Player selected: "; echo $player_name;?>";
  }
</script>

好的,现在$player_name是在组合框中选择的选项。

<form method="POST">
  <select onchange="val()" id="combo"">
  <?php  
    foreach($names as $namearray => $value) { 
  ?>
  <option value="<?php echo $value;?>"><?php echo $value;     ?></option>
  <?php 
    } 
  ?> 
  </select>
  <input type="hidden" name="selected_text" id="selected_text" value="" />
</form>

现在,用户单击“发送”按钮后会发生这种情况:( $player_nam e将为null,因此,sql查询将无法正确执行)

  <?php
    if(isset($_POST['send'])) {
      $sql = "SELECT roleid FROM listrole WHERE name = '$player_name'";
      $result = $conn->query($sql);

      // output data of each row
      while($row = $result->fetch_assoc()) {
        $role_id = $row['roleid'];
        echo $role_id;
      }
  ?>

  <input style='height:30px;' type='submit' name='send' value='Send'>
</form>

0 个答案:

没有答案