Update the content on the webpage to display the SQL data generated by selecting options from various dropdown

My database table is structured like this:

  Name  │ Favorite Color │  Age  │  Pet
────────┼────────────────┼───────┼───────
 Rupert │     Green      │  21   │  Cat
  Mike  │      Red       │  19   │  Dog
 Rachel │     Purple     │  24   │  Cat
 Thomas │      Red       │  21   │  Fish
  ...   |      ...       |  ...  |  ...

I have two dropdowns:

<select>
    <option selected="selected" disabled="disabled">Choose Pet</option>
    <option>Cat</option>
    <option>Dog</option>
    <option>Fish</option>
</select>

<select>
    <option selected="selected" disabled="disabled">Choose Color</option>
    <option>Red</option>
    <option>Green</option>
    <option>Purple</option>
</select>

I am looking to display the individual who matches a specific combination from the two dropdowns.

//if cat and green selected, print Rupert
//if fish and red selected, print Thomas
//etc

I don't have a clear plan on how to approach this. I want to retrieve information through SQL rather than hardcoding it into the page so that any changes in names do not require rewriting code.

$name = $db->prepare("
    SELECT name
        FROM people
        WHERE color = :col
        AND pet = :pet
");
$name->execute(array(
    ':col' => value from one dropdown,
    ':pet' => value from another dropdown
));

This is an example of an SQL query that would be triggered on dropdown change, ensuring that the accurate data is fetched based on the selected combination.

Answer №1

If you anticipate that the data set will grow significantly, it may be more efficient to implement a remote search feature. In this scenario, selections made by users can be sent to a PHP script which will then retrieve and display the corresponding name.

Alternatively, if the data set remains small, you can directly embed the rows into the page as a JSON object. JavaScript can then be used to lookup the selections and dynamically change the displayed names accordingly.

In the case of embedding the data set, you could structure your code like this:

Create JSON Object

var selections = {
  'Cat-Green': 'Rubert',
  'Dog-Red': 'Mike',
  ... 
};

To facilitate easy retrieval of values from selects, assign them IDs like so:

Add HTML Markup

<select id="pet" onchange="update();">
    <option selected="selected" disabled="disabled">Choose Pet</option>
    <option>Cat</option>
    <option>Dog</option>
    <option>Fish</option>
</select>

<select id="color" onchange="update();">
    <option selected="selected" disabled="disabled">Choose Color</option>
    <option>Red</option>
    <option>Green</option>
    <option>Purple</option>
</select>

<span id="result"></span>

Finally, define an update function in JavaScript to populate the result based on selections:

JavaScript Function

function update() {
  var key = $("#pet").val() + '-' + $("#color").val();
  $("#result").text(selections[key]);
}

On the server side, when serving the page, parse the JSON object as shown below:

Complete Script with PHP

<?php
// establish database connection, then
$query  = "SELECT * FROM `favorites` LIMIT 50"; // just to be safe
$result = mysqli_query($link, $query);
$array  = array(); // initialize empty array
while($row=mysqli_fetch_assoc($result)) {
  // Name  │ Favorite Color │  Age  │  Pet
  $array[$row['Pet'] . '-' . $row['Color']] = $row['Name'];
}
$json = json_encode($array); // convert array to JSON string
// closing PHP tag - now proceed to output HTML, JS, and JSON
?>
<!DOCTYPE html>
<html>
<head>
  ...
  <script src=" ... remember to include jQuery ... ></script>
  <script>
    var selections = <?php echo $json; ?>;
    ...
    function update ...
  </script>
</head>
<body>
  <select id="pet" onchange="update();">
  ...
</body>
</html>

Check out this jsbin link for hardcoded JSON data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Axios - Error: Promise Rejected - The request was unsuccessful with a 500 status code

The Axios post request in my code for adding new articles is not going through, and I am encountering an error: Failed to load resource: the server responded with a status of 500 (Internal Server Error) createError.js:17 Uncaught (in promise) Error: Requ ...

Guide on incorporating a thymeleaf custom dialect in an HTML script

Essentially, I am trying to create a dynamic schema using ld+json with thymeleaf. To fetch the URL for the corresponding page, we have set up a custom processor as shown below: public class CustomUrlAttributeTagProcessor extends AbstractAttributeTagProcess ...

Efficient Error Handling in Next.JS with Apollo GraphQL Client

Although the component successfully renders the error state, an uncaught exception is displayed in the console and a dialogue box appears in the browser. How can expected errors be handled to prevent this behavior? import { useMutation, gql } from "@a ...

Is Ursina the right choice for web development?

Looking for a method to compile Ursina for HTML5 using WebAssembly or another technology? I am seeking to make my Ursina Game compatible with Linux & Mac (and potentially Android/iOS with webview), but the current cross-platform compilation options for Py ...

The Twitch API is providing inaccurate channel information

Currently facing an issue while working with the Twitch API. When making a GET request to /api.twitch.tv/helix/search/channels?query=[STREAMER_NAME], it seems to be returning the wrong streamer/user. For instance: /api.twitch.tv/helix/search/channels?quer ...

I'm having trouble getting rid of this stubborn loader on the website

I am currently utilizing the following template: . My objective is to eliminate the preloader progress bar that displays the loading progress of the page in percentage. The files associated with this preloader are as follows: Loader CSS File - www[dot]the ...

Having trouble getting rid of the border-bottom?

I have been attempting to customize the appearance of the React Material UI tabs in order to achieve a design similar to this: https://i.stack.imgur.com/tBS1K.png My efforts involved setting box-shadow for the selected tab and removing the bottom border. ...

Issue with login form in IONIC: Form only functions after page is refreshed

Encountering an issue with my Ionic login form where the submit button gets disabled due to invalid form even when it's not, or sometimes displays a console error stating form is invalid along with null inputs. This problem seems to have surfaced afte ...

Skip nodes in Polymer 1.0 by using ExcludeLocalNames

I recently attempted to transition from Polymer version 0.5 to 1.0 and came across a particular question: Is there a way to exclude certain nodes inside a paper-menu? In the previous version (0.5), you could use the attribute excludedLocalNames to achieve ...

Does the language setting on a browser always stay consistent?

Using javascript, I am able to identify the language of my browser function detectLanguage(){ return navigator.language || navigator.userLanguage; } This code snippet returns 'en-EN' as the language. I'm curious if this i ...

Unraveling Complex JSON Structures in React

Having trouble reading nested JSON data from a places API URL call? Look no further! I've encountered issues trying to access all the information and nothing seems to be coming through in the console. While unnested JSON is not an issue, nested JSON p ...

Conceal elements with a single click of a button

How can I use jQuery to hide all li elements with an aria-label containing the word COMPANY when the Search from documents button is clicked? Here is the HTML code: <ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content" id="ui-id-1" t ...

What is the best way to export all tables from MySQL to a CSV file?

Here is a code snippet that can be used to export a specific table from MySQL to CSV format. But what I really need is a code that can export the entire database table to CSV format. Does anyone have such a code available? Please share it with me. < ...

Execute an AJAX call to remove a comment

Having some trouble deleting a MySQL record using JavaScript. Here is the JavaScript function I am trying to use: function deletePost(id){ if(confirm('Are you sure?')){ $('#comment_'+id).hide(); http.open("get","/i ...

Can you explain the purpose of the search_/> tag used in this HTML code?

I came across this code snippet while working on creating a customized new tab page for Firefox. <input class="searchBar search_google" type="text" name="q" placeholder="Google" search_/> However, I'm confused about the search_ ...

Utilizing TypeScript namespaced classes as external modules in Node.js: A step-by-step guide

My current dilemma involves using namespaced TypeScript classes as external modules in Node.js. Many suggest that it simply can't be done and advise against using namespaces altogether. However, our extensive codebase is structured using namespaces, ...

I'm perplexed as to why my JavaScript code isn't successfully adding data to my database

Recently, I delved into the world of NodeJS and Express. My goal was to utilize Node and Express along with MongoDB to establish a server and APIs for adding data to the database. Specifically, I aimed to write the code in ESmodules syntax for JavaScript. ...

Simple method to send information from an MVC controller to jQuery.ajax

We have a project using ASP.NET MVC that involves sending form data to a controller via jQuery.ajax. Sometimes, the controller may encounter exceptions due to incorrect SQL statements. I want to catch these exceptions in a TRY CATCH block and provide detai ...

Why do I keep encountering a null window object issue while using my iPhone?

Hey there! I've got a React game and whenever the user loses, a new window pops up. const lossWindow = window.open( "", "", "width=500, height=300, top=200, left = 200" ); lossWindow.document.write( & ...

Is it possible to show elements from an ngFor loop just once when dealing with a two-dimensional string array in a display?

I have an array of nested strings, and I am attempting to display the contents of each inner array in a table format. My goal is to have the first table show the values from the first index of each inner array and the second table to display the values fro ...