October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

How to Create a PHP Dropdown List from Database Categories

Fetch category IDs and names with PDO, then render an escaped HTML option for each database row.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Query the category records, then create an HTML <select> with one <option> for each row. Submit each category’s database ID as the option value, show its name as the label, and escape both values before writing them into HTML.

Build the dropdown with PDO

This example assumes a categories table with id and name columns, and an existing PDO connection in $pdo. Change the table and column names to match your schema.

<?php
$stmt = $pdo->query('SELECT id, name FROM categories ORDER BY name');
$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<label for="category">Category</label>
<select name="category_id" id="category" required>
    <option value="">Choose a category</option>
    <?php foreach ($categories as $category): ?>
        <option value="<?= htmlspecialchars((string) $category['id'], ENT_QUOTES, 'UTF-8') ?>">
            <?= htmlspecialchars($category['name'], ENT_QUOTES, 'UTF-8') ?>
        </option>
    <?php endforeach; ?>
</select>

PDO::query() fits this fixed SQL statement because it has no placeholders or user-provided filter. If the query depends on user input, prepare it and bind the input as a parameter rather than inserting that input into the SQL string. See PHP’s PDO::prepare documentation and PDO::query documentation.

fetchAll(PDO::FETCH_ASSOC) returns the remaining rows as an array keyed by column names. If the query returns no rows, the array is empty and the loop produces no category options beyond the prompt. PHP notes that fetchAll() can consume substantial resources for large result sets; for unusually large category lists, limit or redesign the selection. PHP documents fetchAll() behavior and considerations.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep SQL handling and HTML output safe

These are separate jobs: bind user-provided values when they enter SQL, then encode database values when they enter HTML. A prepared statement does not make later HTML output safe.

  • Escape at output. The category ID is placed in a quoted HTML attribute, while the name is placed in HTML text. htmlspecialchars() converts special characters to HTML entities; specifying UTF-8 makes the intended encoding explicit. PHP’s htmlspecialchars() documentation.
  • Submit an identifier, not a label. Use the database key for the option’s value; treat the visible category name as presentation text. Validate the submitted ID on the server against the current records and the user’s permissions when processing the form.
  • Use a label. The <label for="category"> associates a readable name with the select control. The <select> and its <option> elements provide the control and its choices. MDN’s select reference.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Adapt the dropdown to your form

Require a deliberate choice only when needed

The empty prompt option gives users a clear starting point. Keep required only when the form must have a category; remove it if leaving the category unset is valid.

Mark an existing category as selected

When editing a record, compare each category ID with the validated ID stored for that record or supplied by the form. Add the selected attribute to the matching option. Validate the value before using it, and continue escaping the ID and name when outputting them.

Check your database setup

The example expects $pdo to be configured and the relevant database driver to be installed. It does not create the connection or determine your table and column names; those depend on your application’s setup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.