如何获取从下拉菜单中选择的选项并将其插入到mysql表中

时间:2018-05-24 12:27:08

标签: php mysql ajax

我一直在尝试使用带有ajax的php / mysql进行动态下拉菜单。但我是php和ajax的新手,所以我不知道如何将所选选项插入到mysql表中。我创建了一个表单,其中的操作导致insertql.php文件,但它无法正常工作。我正在使用wamp服务器。任何帮助将不胜感激。

index1.php

<?php
//index.php
$connect = mysqli_connect("localhost", "root", "", "projects");
$pname = '';
$query = "SELECT pname FROM project_details GROUP BY pname ORDER BY pname ASC";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
 $pname .= '<option value="'.$row["pname"].'">'.$row["pname"].'</option>';
}
?>
<!DOCTYPE html>
<html>
 <head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>zz
 </head>
 <body>
  <br /><br />

  <div class="container" style="width:600px;">
   <h2 align="center">Dynamic Dependent Select Box using JQuery Ajax with PHP</h2><br /><br />
  <form  method = "POST" action = "insertsql.php" >
 <select name="pname" id="pname" class="form-control action">
    <option value="">Select Project</option>
    <?php echo $pname; ?>
   </select>
   <br />
   <select name="user" id="user" class="form-control action">
    <option value="">Select User Name</option>
   </select>
   <br />
  <input type="submit" name="update" value="Update">
<p id="dem"></p>
<p id="demo"></p>


</form>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 $('.action').change(function(){
  if($(this).val() != '')
  {
   var action = $(this).attr("id");
   var query = $(this).val();
   var result = '';
   if(action == "pname")
   {
    result = 'user';
   }

   $.ajax({
    url:"fetch.php",
    method:"POST",
    data:{action:action, query:query},
    success:function(data){
     $('#'+result).html(data);

    }
   })
  }
 });
});
</script>

fetch.php

    <?php
//fetch.php
if(isset($_POST["action"]))
{
 $connect = mysqli_connect("localhost", "root", "", "projects");
 $output = '';
 if($_POST["action"] == "pname")
 {


  $query = "SELECT fname,lname FROM users WHERE pname = '".$_POST["query"]."' GROUP BY fname";
  $result = mysqli_query($connect, $query);
  $output .= '<option value="">Select User</option>';
  while($row = mysqli_fetch_array($result))
  {
   $output .= '<option value="'.$row["fname"].' '.$row["lname"].'">'.$row["fname"]." ".$row["lname"].'</option>';
  }

 }

 echo $output;

}
?>

1 个答案:

答案 0 :(得分:0)

insertsql.php

<?php
include('sqlconfig.php');

$pname= $_POST['pname'];
$username=$_POST['user'];
$date=$_POST['wdate'];
$hours=$_POST['hours'];
echo "$pname";

echo "<br>$username<br>";
$sql="INSERT INTO worklogging(pname,username,wdate,wkhours) VALUES ('$pname','$username','$date','$hours')";

if(!mysqli_query($con,$sql))
    {echo 'not inserted';}
else
{echo 'Inserted';
}
?>

这是将下拉菜单中的数据插入mysql表的部分。谢谢大家的帮助:))