如何将一个表单元素值传递给php中的mysql查询的下一个表单元素?

时间:2016-11-30 16:03:13

标签: php mysql

我正在尝试执行以下操作:

  1. 用户选择一个座位区
  2. 基于特定区域的座位可用。
  3. 数据库和表格已就位且正确无误。

    我的问题是获取用户为区域选择的值并使用它来查询席位。这是代码:

    <form method="post">
    <?php
    
    $sql = "select Name from Zone";
    $handle = $conn->prepare($sql);
    $handle->execute(array());  
    $res = $handle->fetchAll();
    echo "<select name='Zone'>";
    foreach($res as $row) {
        echo "<option>".$row['Name']."</option>";
    }
    echo "</select>";
    ?>
    
    <?php
    $zone = $_POST['Zone'];
    $sql = "select RowNumber, Zone from Seat WHERE Zone =" .$zone;
    $handle = $conn->prepare($sql); 
    $handle->execute(array());
    $conn = null;
    $res = $handle->fetchAll();
    echo "<select name='Seat'>";
    
    foreach($res as $row) { 
          echo "<option>".$row['RowNumber']."</option>";    
    
    }
    echo "</select>";
    
    ?>
    </form>
    

    这真让我感到沮丧,任何有用的技巧都会有所帮助。提前谢谢。

    [编辑: 由于这是一项评估,我选择将表格分解为其组成部分,并将提交数据从一个元素传递到下一个元素。那就是:

    选择区域 - &gt;提交 - &gt; 使用选定的区域查询数据库中的相对席位,然后填充下一个下拉列表。

    我有这个方法可以工作。它是粗糙的,但它完成了工作和我自己的想法(这是一个评估)。

    然而,Craig和RamRaider为遇到这一挑战的其他人提供了更优雅的解决方案。]

2 个答案:

答案 0 :(得分:1)

此类问题的最佳方法(IMO)是使用Ajax使用某些脚本或其他脚本(在这种情况下是同一页面但可能是完全不同的脚本)从数据库请求数据< / p>

HTML页面上的初始下拉菜单将有一个事件监听器(onchange),当用户从菜单中选择时,它将触发ajax请求。以下未经过测试,但也许应该提出一个想法。

<?php
    /*
        db & other includes etc
    */

    /*
        Ajax POST request is processed here
    */
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['zone'] ) ){

        /* clean output buffers to ensure no unexpected data is in the response */
        ob_clean();

        /* Write data/response to an array */
        $response=array();


        /* !! By directly embedding variables in the sql you open your code to SQL injection!! */
        $sql = "select `RowNumber`, `Zone` from `Seat` WHERE `Zone` ='" . $_POST['zone'] ."';";
        $handle = $conn->prepare( $sql ); 
        $handle->execute();
        $conn = null;
        $res = $handle->fetchAll();


        /* Process the recordset: add an option for each row found */
        foreach( $res as $row ) { 
            $response[]="<option>".$row['RowNumber'];    
        }



        /* Send the response data to the ajax callback function */
        exit( implode( PHP_EOL, $response ) );
    }
?>


<!doctype html>
<html>
    <head>
        <title>Ajax menu</title>
        <script type='text/javascript' charset='utf-8'>

            /* Simple ajax function to send request to same page and fetch new data from db */
            function fetchrows( name ){
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 ) plotrows.call( this, xhr.response );
                };
                xhr.open( 'POST', location.href, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( 'zone='+value );
            }

            /* ajax callback */
            function plotrows( response ){
                document.getElementById('seat').innerHTML=response;
            }
        </script>
    </head>
    <body>
        <form method="post">
        <?php

            /*

                Initial dropdown menu with an `onchange` event handler that triggers 
                an ajax request to the same script but calls a sql command to generate
                the menu contents for the second menu.

            */


            $sql = "select `name` from `zone`";
            $handle = $conn->prepare( $sql );
            $handle->execute();  
            $res = $handle->fetchAll();



            echo "<select name='Zone' onchange='fetchrows( this.value )'>";
            foreach( $res as $row ) {
                echo "<option>".$row['Name'];
            }
            echo "</select>";
        ?>

        <!-- This will be populated by javascript with appropriate options -->
        <select name='seat' id='seat'></select>


        <!--

            More form content and further HTML....

        -->
        </form>
    </body>
</html>

要在没有AJAX的情况下获得相同的最终结果(或多或少),您可以使用javascript函数将zone附加到查询字符串并在构造sql时使用它。

<!doctype html>
<html>
    <head>
        <title>Not ajax menu</title>
        <script type='text/javascript' charset='utf-8'>
            function fetchrows( name ){
                location.search='zone='+name
            }
        </script>
    </head>
    <body>
        <form method="post">
        <?php

            $sql = "select `name` from `zone`";
            $handle = $conn->prepare( $sql );
            $handle->execute();  
            $res = $handle->fetchAll(); 

            echo "<select name='Zone' onchange='fetchrows( this.value )'>";
            foreach( $res as $row ) {
                echo "<option>".$row['Name'];
            }
            echo "</select>";
        ?>



        <select name='seat'>
        <?php
            if( $_SERVER['REQUEST_METHOD']=='GET' && !empty( $_GET['zone'] ) ){

                /* !! By directly embedding variables in the sql you open your code to SQL injection!! */
                $sql = "select `RowNumber`, `Zone` from `Seat` WHERE `Zone` ='" . $_GET['zone'] ."';";
                $handle = $conn->prepare( $sql ); 
                $handle->execute();
                $conn = null;
                $res = $handle->fetchAll();


                foreach( $res as $row ) { 
                      echo="<option>".$row['RowNumber'];    
                }
            }
        ?>
        </select>


        <!--

            More form content and further HTML....

        -->
        </form>
    </body>
</html>

答案 1 :(得分:1)

考虑这个使用HTML,PHP,MySQL和一个平面Javascript命令的工作示例:

<强>的index.php

<?php
// Include the class that handles the database interactivity
require_once 'Database.php';
// Initialise the database
$Database = new Database();
// Get the list of Zones
$Zones = $Database->getZones();

// ZONE
if (isset($_POST['Zone'])) {
  // You could validate and whitelist entries here if you wanted
  if (!in_array($_POST['Zone'], $Zones)) {
    $response = 'Sorry but that was not a valid selection';
  }
  // Passed validation
  else {
    // Get the corresponding Seats
    $Seats = $Database->getSeats($_POST['Zone']);
    // Store the Zone selection
    $selectedZone = $_POST['Zone'];
    // Set the response
    $response = 'Viewing seats for '.$_POST['Zone'];
  }
}
// SEAT
if (isset($_POST['Seat'])) {
  printf('Zone that was chosen: '.$selectedZone);
  printf('<br>');
  printf('Seat that was chosen: '.$_POST['Seat']);
  exit;
}
// This deals with initally loading the page
if (!isset($_POST['Zone']) && !isset($_POST['Seat'])) {
  // Open variables
  $response = '';
  $selectedZone = 'n/a';
  $Seats = array();
}

// You could move the code from here onwards into another file
// So you have a template like: 
// require_once 'view.php'; which has a form that posts to index.php

// Start generating the page html
$page = '
<!DOCTYPE html>
<html>
<head>
  <title>Awesome Page!</title>
</head>
<body>

<form method="POST" action="index.php">
';

// If theres a response to display
if (strlen($response) > 0) {
  $page .= '
    <p>'.$response.'</p>
  ';
}

// Dealing with the Zone selection
$page .= '
<p>Zones</p>
<select name="Zone" onchange="this.form.submit()">
  <option value="">Please select an option</option>
';
// Itterate over the Zones
foreach ($Zones as $name) {
  // If this is the selected Zone
  if ($selectedZone == $name) {
    $page .= '
      <option selected value="'.$name.'">'.$name.'</option>
    ';
  }
  // This is not a selected Zone
  else {
    $page .= '
      <option value="'.$name.'">'.$name.'</option>
    ';
  }
}
$page .= '
</select>
';

// Dealing with the Seat selection
if (count($Seats) > 0) {
  $page .= '
  <p>Seats</p>
  <select name="Seat" onchange="this.form.submit()">
    <option value="">Please select an option</option>
  ';
  // Itterate over the Seats
  foreach ($Seats as $RowNumber) {
    $page .= '
      <option value="'.$RowNumber.'">Row Number: '.$RowNumber.'</option>
    ';
  }
  $page .= '
  </select>
  ';
}
// Theres no Seats yet as Zone is not selected
else {
  $page .= '
    <p>Please select a Zone first.</p>
  ';
}
$page .= '
</form>

</body>
</html>
';

// Display the page
echo $page;

<强> database.php中

<?php
class Database
{
  // Active connection
  private $link;

  // This fires when you call new Database();
  public function __construct()
  {
    $this->doConnect();
  }

  private function doConnect()
  {
    // Define database details
    $DBHost = 'localhost';
    $DBUser = 'username';
    $DBPass = 'password';
    $DBName = 'database_name';
    // Create a database connection for PHP to use
    $this->link = mysqli_connect($DBHost, $DBUser, $DBPass);
    // Preform from tasks to ensure the connection is active
    if (!$this->link) {
      echo 'Error: Unable to connect to MySQL' . '<br>';
      echo 'Debugging errno: ' . mysqli_connect_errno() . '<br>';
      echo 'Debugging error: ' . mysqli_connect_error() . '<br>';
      exit;
    }
    // Sets encoding type to uft8
    if (!mysqli_set_charset($this->link, 'utf8')) {
      $this->processError();
    }
    // Set database that is in use (makes queries shorter to write)
    if (!mysqli_select_db($this->link, $DBName)) {
      $this->processError();
    }
  }

  public function getZones()
  {
    // Stores the result
    $Zones = array();
    // Build query
    $query = 'SELECT `name` ';
    $query .= 'FROM `Zone` ';
    // Prepare the statement
    if (!$stmt = $this->link->prepare($query)) { $this->processError(); }
    // Execute the query
    if (!$stmt->execute()) { $this->processError(); }
    // Bind variable to query values
    if (!$stmt->bind_result($name)) { $this->processError(); }
    // Itterate over the rows
    while ($stmt->fetch()) {
      // Add this Zones name to the result
      $Zones[] = $name;
    }
    // Close the statement
    $stmt->close();

    // Return the result
    return $Zones;
  }

  public function getSeats($selectedZone)
  {
    // Stores the result
    $Seats = array();
    // Build query
    $query = 'SELECT `RowNumber` ';
    $query .= 'FROM `Seat` ';
    $query .= 'WHERE `Zone` = ? ';
    // Prepare the statement
    if (!$stmt = $this->link->prepare($query)) { $this->processError(); }
    // Bind in form values to prevent sql injection
    if (!$stmt->bind_param('s', $selectedZone)) { processError($link); } // NB: Assumed this to be a string but might be an integer, if so use i instead of s
    // Execute the query
    if (!$stmt->execute()) { $this->processError(); }
    // Bind variable to query values
    if (!$stmt->bind_result($RowNumber)) { $this->processError(); }
    // Itterate over the rows
    while ($stmt->fetch()) {
      // Add this RowNumber to the Seats
      $Seats[] = $RowNumber;
    }
    // Close the statement
    $stmt->close();

    // Return the result
    return $Seats;
  }

  private function processError()
  {
    echo 'Error: Unable to connect to MySQL' . '<br>';
    echo 'Debugging errno: ' . $this->link->errno . '<br>';
    echo 'Debugging error: ' . $this->link->error . '<br>';
    exit;
  }
}

基本上,我们的PHP位在顶部处理获取数据和表单提交,然后我们在其下面有html模板,其中包含一个提交给自己的表单。

模板(逻辑视图类型)将利用由Database类(模型逻辑类型)辅助的第一位(控制器类型的逻辑)提供的数据。

因此,这是一个非常简单的MVC模式实现。

Javascript的使用非常简单,以便检测选择值的变化,然后提交表单:onchange="this.form.submit()"

我尽可能地对代码进行评论,以便增加对您的理解,但如果您有任何疑问,请随时询问:)