I have two tables - companies and clients. They each have an identical row labeled company_id
so I can assign a company to each client.
First a company is created.
Then the client is created and the company is associated with it in the process.
Then an order is created...
For orders, I have a table named orders. When inserting data into the table, I have a form with two dropdown boxes. The first dropdown is to select the company the order is for. This is populated using the following:
$getCompany = mysqli_query($db, "SELECT * FROM companies ORDER BY company_name ASC");
<label for="company_id">Company</label>
<select class="form-control" name="company_id" id="company_id">
<option disabled selected></option>
<?php
// If there are results, output each row.
if($getCompany) {
while($company = mysqli_fetch_assoc($getCompany)) { ?>
<option value="<?php echo $company['company_id']; ?>">
<?php echo $company['company_name']; ?>
</option>
<?php }
}
?>
</select>
The second dropdown is identical, but instead calls the clients' names.
$getClient = mysqli_query($db, "SELECT * FROM clients ORDER BY client_fname ASC");
<select class="form-control" name="client_id" id="client_id">
<option disabled selected></option>
<?php
// If there are results, output each row.
if($getClient) {
while($client = mysqli_fetch_assoc($getClient)) { ?>
<option value="<?php echo $client['client_id']; ?>">
<?php echo $client['client_fname']." ".$client['client_lname']; ?>
</option>
<?php }
}
?>
</select>
If I select CompanyA from the first dropdown, how can I show only the clients associated with that selection in the second dropdown?
Use ajax like this
Javascript
$('.company_id').change(function()
{
var company_id = $('.company_id').val();
var request = $.ajax({
url: "your_ajax.php",
method: "POST",
data: {
company_id: company_id,
action: 'get_clients_by_company_id'
}
});
request.done(function (msg) {
$('#client_id').val(msg);
});
});
PHP CODE IN YOUR AJAX
<?php
if (isset($_POST['action']) and $_POST['action'] == 'get_clients_by_company_id') {
$company_id = $_POST['company_id'];
if (!empty($company_id)) {
$getClient = mysqli_query($db, "SELECT * FROM clients WHERE company_id = '$company_id' ORDER BY client_fname ASC");
while ($client = mysqli_fetch_assoc($getClient)) {
?>
<option value="<?=$client['client_id']; ?>">
<?=$client['client_fname'] . " " . $client['client_lname']; ?>
</option>
<?php
}
}
}
?>