Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/250.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对于php中的mysql查询,如何将一个表单元素值传递给下一个表单元素?_Php_Mysql - Fatal编程技术网

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

对于php中的mysql查询,如何将一个表单元素值传递给下一个表单元素?,php,mysql,Php,Mysql,我正在努力做到以下几点: 用户选择一个座位区 基于该区域,特定座位将可用 数据库和表已就位且正确无误 我的问题是获取用户为区域选择的值,并使用它来查询座位。代码如下: <form method="post"> <?php $sql = "select Name from Zone"; $handle = $conn->prepare($sql); $handle->execute(array()); $res = $handle->fetchAll();

我正在努力做到以下几点:

  • 用户选择一个座位区
  • 基于该区域,特定座位将可用
  • 数据库和表已就位且正确无误

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

    <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>
    
    
    
    这真的让我很沮丧,任何有助于取得突破的有用提示都会非常有用。提前谢谢

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

    选择区域->提交-> 使用所选区域查询数据库中的相对座位,并填充下一个下拉列表

    我已经用这种方法工作了。它很粗糙,但能完成工作,这是我自己的想法(这是一个评估)

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

    解决这类问题的最佳方法(IMO)是使用
    Ajax
    使用某种脚本或其他脚本(在这种情况下,相同的页面可能是完全不同的脚本)从数据库请求数据

    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>
    

    考虑这个使用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;
    
    <?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;
      }
    }
    

    Hello and welcome to SO:)我曾经对如何完成类似的事情做了一次很好的解释,这可能会对您有所帮助:但是看看您的用例,您似乎需要一些Javascript来检测select何时更改,并基于此提交表单?下面是一个例子:要学习的内容很多,从PHP网页脚本的生命周期开始,这也是错误的
    $sql=“选择行数,从座位开始的区域,其中区域=”.$Zone
    作为文本值,需要像下面这样用引号括起来
    $sql=“select RowNumber,Zone from Seat WHERE Zone=”$Zone'你知道你错过了选项的值属性,是吗?因此,不会为任何选择的选项提交任何内容。是的,但是,唉,我不被允许,我只能使用JS、PHP和mySQL,因为这是我正在评估的。呃。。。ajax是javascriptWell,它与xml的关系越来越密切。我们已经被告知不能使用它。必须坚持纯JS。刚刚看到编辑。谢谢你,伙计。明天我会详细复习,看看能学到什么。但是有一件事是肯定的,我不能容易受到注入攻击,或者我会失去分数。为了避免sql注入(f)检查,请使用准备好的语句,并且作为额外的预防措施,对用户输入进行清理。非常感谢您花时间这么做。我明天将进行取证。@ScheurichGolzari供您参考,对代码进行了一些修改,以解决一些逻辑问题,我仍然看到一些问题,但认为它提供了一个很好的示例,说明您可能如何处理问题。
    
    <?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;
      }
    }