在PHP中使用选定的选项作为变量选择下拉列表

时间:2017-11-08 09:33:37

标签: php html sql

我使用PHP从Azure SQL数据库中提取数据,并成功创建了一个下拉(选择)框,其中包含从数据库中提取的选项。 SQL查询返回2列,标题& Cycle_ID。

我已将Title设置为文本字符串,将Cycle_ID设置为值。 我现在想要将当前选择的值(Cycle_ID)存储在变量(MyVariable)中,我将在SQL查询中使用我创建的下一个下拉框,即WHERE Cycle_ID = MyVariable。 这样,当用户通过我的下拉框向下工作时,用户逐渐缩小他们的选择范围。 我目前的代码如下,但我不知道如何创建当前选择并将其存储到MyVariable。

<?php
//create the database connection and define the query
$serverName = "myserver";
$connectionOptions = array(
    "Database" => "mydatabase",
    "Uid" => "mysqlaccount",
    "PWD" => "mypassword"
);
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);

//defines cycle query
$cyclesql= "SELECT [Cycle_ID]
      ,[Title]
  FROM [ods].[Cycle]
  WHERE End_Date > DATEADD(month,-6,GETDATE()) AND Updated IS NOT NULL
  ORDER BY Cycle_ID Asc";
$cycleResults= sqlsrv_query($conn, $cyclesql);

if ($cycleResults == FALSE)
    echo (sqlsrv_errors());
?>

<html>
<body>

<form action="cyclefile.php" method="post"> 
<div id="select">
<p>Select the week:</p><select name='Week'>
<option value="">Select...</option>
<?php
//starts loop
while ($row = sqlsrv_fetch_array($cycleResults, SQLSRV_FETCH_BOTH)) {
//defines cycle variable
$cycle = $row['Title'];
//defines cycle_id variable
$cycle_id = $row['Cycle_ID'];
//displays cycle variable as option in select (dropdown) list and cycle_id as value 
echo '<option value="'.$cycle_id.'">'.$cycle.'</option>';
}
?>
</select>
</div>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

我建议您在选择时进行ajax调用并传递所选值以在另一个可以运行查询的文件中处理结果。

<select name="cycle_data" id="cycle_id">
   <option value="cycle1" > Cycle 1</option>
   <option value="cycle2" >Cycle 2</option>
</select>

然后让我们做一个脚本:

 <script type="text/javascript">
   $(document).ready(function(){ 
   $("#cycle_id").change(function(){ 
   var cycle_data = $(this).val(); 
   var dataString = "cycle_data="+cycle_data; 

    $.ajax({ 
    type: "POST", 
    url: "get-data.php", 
    data: dataString, 
    success: function(result){ 
      // Process your result here
    }
    });
    });
   });
</script>