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.
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.
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.
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();
}
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));
}
});
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 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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| saddam | 14-06-2014 |
| thanks this code is solve my problem | |
01-07-2021 | |
| Thanks for this | |