hey guys i was woundering if it was possible to connect and grab infromation from a database triggered by a drop down menu click in php .... or will i have t o learn java and figure it out there .. im sure there is a way tho somone help meo ut im new to php ;)

Dani AI

Generated

A concise, modern path forward: and were right to point at client-side requests and Ajax; ’s server-rendered select is a perfectly valid non-JS fallback. For a clean, secure setup today use a small PHP endpoint that returns JSON (PDO + prepared statements), and a client-side fetch() handler that repopulates the second dropdown on the change event. That keeps DB logic on the server, minimizes page reloads, and avoids the old mysql_* API.

Example server endpoint (PHP + PDO) — returns JSON for a given parent id:

<?php
// endpoint.php
header('Content-Type: application/json; charset=utf-8');

$dsn = 'mysql:host=localhost;dbname=mydb;charset=utf8mb4';
$pdo = new PDO($dsn, 'dbuser', 'dbpass', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

$parent = isset($_GET['parent']) ? $_GET['parent'] : '';
if (!ctype_digit((string)$parent)) { echo json_encode([]); exit; }

$stmt = $pdo->prepare('SELECT id, label FROM items WHERE parent_id = ? ORDER BY label');
$stmt->execute([$parent]);
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));

Client-side (plain JS, minimal):

document.getElementById('parentSelect').addEventListener('change', function () {
  const parent = this.value;
  fetch('/endpoint.php?parent=' + encodeURIComponent(parent))
    .then(r => { if (!r.ok) throw r.statusText; return r.json(); })
    .then(items => {
      const child = document.getElementById('childSelect');
      child.innerHTML = '<option value="">-- choose --</option>';
      items.forEach(it => {
        const o = document.createElement('option');
        o.value = it.id;
        o.textContent = it.label;
        child.appendChild(o);
      });
    })
    .catch(err => console.error('Error loading options:', err));
});

Quick tips and troubleshooting

  • Use prepared statements and validate inputs server-side (see PHP PDO manual: https://www.php.net/manual/en/book.pdo.php).
  • Set Content-Type: application/json and ensure no PHP warnings/whitespace before output (warnings break JSON). Turn off display_errors in production and log instead.
  • Prevent XSS by inserting text via textContent, not innerHTML.
  • If the JS is on another origin, add proper CORS headers.
  • For security guidance on input validation see OWASP: https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html.
  • Keep a server-rendered "sticky" select as showed for a graceful fallback when JavaScript is disabled.

Recommended Answers

All 3 Replies

Yes this is a smiple way but when your data become too important, you may wish to use Ajax combined with your menu. This way you can make calls to your server which gives back the data requested.

Here is an examlpe of how I used a dynamic select box using PHP.

In this case I have a table called "facilities" and display the information in the select options by calling the information from the db.
I further set the variable "$sticky" to retain the values upon error checking so the user has the value they originally entered.

<?php
$result = mysql_query("SELECT * FROM facilities ORDER BY Street1 ASC") or 
die(mysql_error());
$sticky= '';
if (isset($_POST['facility']))
$sticky = ($_POST['facility']);
$pulldown1 = '<select name="facility">';
$pulldown1 .= '<option></option>';
 while($row = mysql_fetch_array($result))
            {
if($row['FacilitiesID'] == $sticky) {
$pulldown1 .= "<option selected value=\"{$row['FacilitiesID']}\">
{$row['Street1']}&nbsp;-&nbsp;
{$row['City']}&nbsp;-&nbsp;
{$row['Name']}
</option>\n";
} else {
$pulldown1 .= "<option value=\"{$row['FacilitiesID']}\">
{$row['Street1']}&nbsp;-&nbsp;
{$row['City']}&nbsp;-&nbsp;
{$row['Name']}
</option>\n";
}
}
$pulldown1 .= '</select>';
echo $pulldown1;    
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.