简体   繁体   English

查询MySQL数据库,然后在提交表单后显示检索到的文本

[英]Query a MySQL Database then display retrieved text after form submit

I am attempting to submit a form immediately after a selection is made from a drop-down menu. 从下拉菜单中进行选择后,我试图立即提交表单。 After the form is submitted I want to send a query to a MySQL database based on the selection from the drop-down and display the retrieved text. 提交表单后,我想基于下拉菜单中的选择向MySQL数据库发送查询,并显示检索到的文本。

Currently, with what I have below, nothing is displayed, no errors are thrown. 目前,在下面的内容中,什么也没有显示,也没有抛出任何错误。 The JS submit event handler works but after the page reloads the new text is not displayed. JS提交事件处理程序可以工作,但是在页面重新加载后,不会显示新文本。

Any help is greatly appreciated. 任何帮助是极大的赞赏。

The JS for submitting the form: 提交表单的JS:

$(".platformSelectDropDown").change(function() {
  $('.platformSelectForm').submit();
});

PHP to run after the form is submitted: 提交表单后运行的PHP:

if($_SERVER['REQUEST_METHOD'] == 'POST') {
  $platform = $_POST['platformSelectDropDown'];
  $description = call_data($tableName, $platform)['Description'];
  $application = call_data($tableName, $platform)['Application'];
}

PHP Function for querying and returning the data: 用于查询和返回数据的PHP函数:

function call_data($tableName, $col, $platformName) {
  include('connection.php');
  $sql = 'SELECT * FROM $tableName WHERE platform_name = $platformName';
  try {
    return $db->query($sql);
  }
  catch (Exception $e) {
    echo "Error! " . $e->getMessage() . "<br/>";
    return array();
  }
}

The Form: 表格:

<form class="platformSelectForm" method="post" action="index.php">
  <select name="platformSelectDropDown" class="platformSelectDropDown">
    ...
  </select>
  <ul class="indent">
    <li><?php echo($description); ?></li>
    <li><?php echo($application); ?></li>
  </ul>
</form>

I believe the code below will do what you want, with some improvements in security and functionality. 我相信下面的代码将实现您想要的功能,并在安全性和功能上有所改进。 However, please note that it's not clear to me from your code where $tableName is being set, so I just hard-coded that to be my test table. 但是,请注意,从您的代码来看,尚不清楚设置$tableName位置,因此我只是将其硬编码为我的测试表。 I intermingled the php and html, because it made it easier for me to work through the problem and I think it will make it easier for you to follow my solution. 我将php和html混合在一起,因为它使我更容易解决问题,并且我认为它将使您更容易遵循我的解决方案。 There's no reason why you can split it back out and functionize the php portions, similar to your original approach, if you prefer. 如果您愿意,没有理由可以将其拆分回去并实现php部分的功能,类似于您的原始方法。 Check it out: 看看这个:

<html>
    <body>
        <form class="platformSelectForm" id="platformSelectForm" method="post">

                <?php

                    // Get which dropdown option is selected, if any, so can keep selected on page reload 
                    if(!isset($_POST['platformSelectDropDown'])) {

                        // Not postback, default to first option ("Select One")
                        $p0Select = ' selected';
                        $p1Select = '';
                        $p2Select = '';

                    } else {

                        // Is postback
                        // Set variables for query below
                        $tableName = 'tbl_platforms_1';
                        $platformName = $_POST['platformSelectDropDown'];

                        // set dropdown selection to whatever was select at form submission 
                        if($platformName == 'Platform_1') {
                            $p1Select = ' selected';
                        } elseif ($platformName == 'Platform_2') {
                            $p2Select = ' selected';
                        } else {
                            $p0select = ' selected';
                        }
                    }

                    ?>

                    <select name="platformSelectDropDown" class="platformSelectDropDown" onchange="document.getElementById('platformSelectForm').submit()">
                        <option value="Select_One"<?php echo $p0Select; ?>>Select One</option>
                        <option value="Platform_1"<?php echo $p1Select; ?>>Platform 1</option>
                        <option value="Platform_2"<?php echo $p2Select; ?>>Platform 2</option>
                    </select>


                    <?php

                        // If dropdown value is set and does not equal "Select_One"
                        if(isset($_POST['platformSelectDropDown'])&& $_POST['platformSelectDropDown'] != 'Select_One') {

                            ?>
                            <ul class="indent">
                            <?php

                                try {

                                    // Set database parameters 
                                    // Replace these values with appropriate values for your database
                                    // (okay to use an include like you did originally)
                                    $dbhost = 'your_database_host';
                                    $dbname = 'your_database_name';
                                    $dbuser = 'your_database_user';
                                    $dbpass = 'your_database_user_password';

                                    // Create PDO
                                    $conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
                                    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
                                    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                                    // Prepare SQL statement and bind parameters
                                    $stmt = $conn->prepare("SELECT * FROM $tableName WHERE platform_name = :platformName");
                                    $stmt->bindValue(':platformName', $platformName, PDO::PARAM_STR);

                                    // Execute statement and return results in an associative array (e.g., field_name -> value)
                                    $stmt->execute();
                                    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

                                    // Close Connection
                                    $conn = null;

                                    // For each row that was returned, output results
                                    for ($i = 0; $i < count($results); $i++) {
                                        echo '<li>' .$results[$i]['Description'] .'</li>';
                                        echo '<li>' .$results[$i]['Application'] .'</li>';
                                    }

                                } catch (Exception $e) {
                                    echo '<li>Error! ' .$e->getMessage() . '</li>';
                                }
                            ?>
                            </ul>
                            <?php
                        };
                ?>
        </form>
    </body>
</html>

Code I used to setup test: 我用来设置测试的代码:

DROP TABLE IF EXISTS tbl_platforms_1;
CREATE TABLE IF NOT EXISTS tbl_platforms_1 (
    id int AUTO_INCREMENT NOT NULL,
    platform_name varchar(20),
    Description varchar(20),
    Application varchar(20),
    PRIMARY KEY (id)
);

INSERT INTO 
    tbl_platforms_1
        (platform_name, Description, Application)
    VALUES 
        ('Platform_1', 'Description 1', 'Application 1'),
        ('Platform_2', 'Description 2', 'Application 2');

If this solves your problem, please remember to mark as answered, so everyone will know you no longer need help (and so I'll get rewarded for the hour I spent coming up with this solution :-). 如果这解决了您的问题,请记住标记为已回答,这样每个人都将知道您不再需要帮助(因此,我花在提出此解决方案上的一小时便会得到回报:-)。 If this doesn't solve your problem, please provide as much detail as possible as to how the current results differ from your desired results and I will try to revise it to fit your needs. 如果这样做不能解决您的问题,请提供尽可能多的详细信息,说明当前结果与您期望的结果有何不同,我将尝试对其进行修改以满足您的需求。 Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM