Is it possible to automatically populate a dependent Foreign Key based on a select option in PHP?

Yes, it is possible to automatically populate a dependent Foreign Key based on a select option in PHP by using AJAX. When a user selects an option from a dropdown menu, an AJAX request can be sent to a PHP script that retrieves the corresponding Foreign Key value and updates the dependent Foreign Key field in the database.

// HTML code for a dropdown menu and a dependent field
<select id="parent_select">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
</select>
<input type="text" id="dependent_field">

// AJAX script to send a request to update the dependent field
<script>
$(document).ready(function(){
  $('#parent_select').change(function(){
    var parentValue = $(this).val();
    $.ajax({
      url: 'update_dependent_field.php',
      type: 'POST',
      data: { parentValue: parentValue },
      success: function(data){
        $('#dependent_field').val(data);
      }
    });
  });
});
</script>

// PHP script (update_dependent_field.php) to handle the AJAX request
<?php
// Connect to database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Retrieve the dependent Foreign Key value based on the selected option
$parentValue = $_POST['parentValue'];
$stmt = $pdo->prepare("SELECT dependent_field FROM your_table WHERE parent_field = :parentValue");
$stmt->bindParam(':parentValue', $parentValue);
$stmt->execute();
$dependentValue = $stmt->fetchColumn();

// Return the dependent Foreign Key value
echo $dependentValue;
?>