hello,

i have a mysql database which i use a php script to search and display results with fields make, model, price, year and would like to add extra functionality with presumably javascript to add a drop down form field as when a particular make is selected from the list then it auto displays the relevant models only for that make.

help appreciated !

pabzzmike

Dani AI

Generated

Short summary and a practical pattern that complements what asked for and what started: prebuilding client-side arrays from PHP works for tiny datasets, but a more robust approach is to fetch only the models you need when a make is selected. That keeps pages small, avoids embedding lots of data, and separates concerns (PHP => JSON API, JS => DOM update). 's "try it" comment is good — this is a simple change to implement.

Server: create a small JSON endpoint that returns models for a given make id. Use prepared statements (PDO or mysqli) and send a proper JSON content-type. Example server skeleton (replace DSN/credentials and table/column names):

<?php
// get_models.php
if (!isset($_GET['make_id'])) { http_response_code(400); echo json_encode(['error'=>'missing make_id']); exit; }
$makeId = (int)$_GET['make_id'];
$pdo = new PDO('mysql:host=HOST;dbname=DB;charset=utf8mb4','USER','PASS',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
$stmt = $pdo->prepare('SELECT id, model_name FROM models WHERE make_id = ? ORDER BY model_name');
$stmt->execute([$makeId]);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));

Client: add a change handler on the make <select>, fetch the JSON, and build options safely (use textContent to avoid XSS). Example flow:

makeSelect.addEventListener('change', async () => {
  modelSelect.disabled = true;
  modelSelect.innerHTML = '<option>Loading...</option>';
  try {
    const res = await fetch('/get_models.php?make_id=' + encodeURIComponent(makeSelect.value));
    const items = await res.json();
    modelSelect.innerHTML = '';
    if (!items.length) modelSelect.innerHTML = '<option>No models</option>';
    else items.forEach(m => { const o=document.createElement('option'); o.value=m.id; o.textContent=m.model_name; modelSelect.appendChild(o); });
  } catch (err) {
    modelSelect.innerHTML = '<option>Error loading</option>'; console.error(err);
  } finally { modelSelect.disabled = false; }
});

Tips/troubleshooting: check the browser Network/Console if no data; verify the endpoint returns valid JSON and the Content-Type header; use prepared statements to prevent SQL injection; provide a server-side fallback for no-JS users (submit form and re-render models on the server); disable the model select until populated; show a friendly message when no models exist; consider caching responses for frequently requested makes. This approach scales better than embedding large JS arrays and is easier to maintain.

Recommended Answers

All 2 Replies

hello,

i have a mysql database which i use a php script to search and display results with fields make, model, price, year and would like to add extra functionality with presumably javascript to add a drop down form field as when a particular make is selected from the list then it auto displays the relevant models only for that make.

help appreciated !

pabzzmike

<?php

//from your  2 resultsets containing the models & makes 
//create a models array for each make
$models = array();
while($makerow = mysql_fetch_assoc($makeresultset)){
    $j = 0;
    while($row = mysql_fetch_assoc($modelresultset)){
           if($row['make_name'] == $makerow['make_name'])
                $models[$j++] = "'".$row['model_name']."'";
    }
}

//joiining the array items to form a string separated by commas
//overally we create an array of such strings
$newModels = array();
for($i=0; $i<count($models); $++){
       $newModels[$i] = implode(", ", $models[$i]);
}

//initialising the javascript array
$modelString = "" ;
for($i=0; $i<count($newModels); $++){
       $modelString .= "modelArray[$i] = $newModels[$i]; " ;
}

echo "
  <script language=javascript>
    function fillArea(){
      var modelArray = new Array();
      $modelString
     var value = document.getElementById('make').value;
     var dest = document.getElementById('output');
     switch(value){
        case '1': dest.innerHTML = 'make 1 stuff' ; break;//output the modelArry[1] items here
        case 2':dest.innerHTML ='make 2 stuff'; break;//output the modelArry[2] items here
        case 'n': dest.innerHTML ='make 3 stuff'; break;//output the modelArry[n] items here
     }
  </script>
     "
?>
<form>
  <select id=make onchange=fillArea()>
    <option value='1'>Make 1</option>
    <option value='2'>Make 2</option>
    <option value='n'>Make 3</option>
  </select>
<form>
<div id=output>
</div>

Not revised - though that's the idea i usually use !!

code looking fine. try it.

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.