Populate Dependent Dropdowns from MySQL Data

The original database example generated JavaScript source directly from PHP and loaded that PHP file through a <script src> tag. That demonstrates how server data can become dropdown options, but the downloadable example has now been updated to a clearer split: PHP returns JSON, JavaScript fetches the data, and the browser builds the two selects.

Start with the client-side dependent dropdown tutorial to understand the listbox logic before adding a database.

Table of Contents

Store Categories and Subcategories in MySQL Top ↑

The existing example uses a category table with cat_id and category, plus a subcategory table that connects rows through cat_id. The download keeps that two-table structure and includes an SQL dump.

Return Structured JSON from PHP Top ↑

Use PDO in the downloadable example instead of the removed legacy mysql_* functions. The endpoint queries categories, loads matching subcategories, and returns JSON.

<?php
header("Content-Type: application/json; charset=utf-8");
require __DIR__ . "/config.php";

$stmt = $pdo->query("SELECT cat_id, category FROM category ORDER BY category");
$categories = $stmt->fetchAll();

$sub = $pdo->prepare("SELECT subcategory FROM subcategory WHERE cat_id = ? ORDER BY subcategory");
foreach ($categories as &$category) {
    $sub->execute([$category["cat_id"]]);
    $category["subcategories"] = $sub->fetchAll(PDO::FETCH_COLUMN);
}

echo json_encode($categories, JSON_UNESCAPED_UNICODE);

For database connection concepts, the original page links to MySQL connection guidance.

Fetch the Dropdown Data in JavaScript Top ↑

async function loadCategories() {
  const response = await fetch("categories.php", { headers: { Accept: "application/json" } });
  if (!response.ok) throw new Error("Unable to load categories");
  return response.json();
}

Populate the Two Select Elements Top ↑

const data = await loadCategories();
for (const category of data) {
  categorySelect.add(new Option(category.category, category.cat_id));
}

categorySelect.addEventListener("change", () => {
  const category = data.find(item => String(item.cat_id) === categorySelect.value);
  subcategorySelect.replaceChildren(new Option("Subcategory", ""));
  for (const item of category?.subcategories ?? []) {
    subcategorySelect.add(new Option(item, item));
  }
});

Database and Output Safety Top ↑

Keep credentials outside public output, use PDO or MySQLi rather than removed mysql_* APIs, use prepared statements when values enter SQL queries, and return JSON with the correct content type. When option labels are created with new Option(), browser text handling avoids treating labels as HTML.

Download the Updated Database Example Top ↑

Download the complete database-backed dependent-dropdown example and SQL dump.

The archive includes configuration, a JSON endpoint, a JavaScript file, an HTML page and sample table data. Replace the sample database credentials before running it.

Listbox JavaScript validation




Subscribe to our YouTube Channel here



plus2net.com







saddam

14-06-2014

thanks this code is solve my problem

01-07-2021

Thanks for this



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer