简体   繁体   中英

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.

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.

Any help is greatly appreciated.

The JS for submitting the form:

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

PHP to run after the form is submitted:

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:

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. 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. There's no reason why you can split it back out and functionize the php portions, similar to your original approach, if you prefer. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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