How can the issue of not being able to use Foreign Keys be addressed when storing selections as IDs in a single field?

When storing selections as IDs in a single field, the issue of not being able to use Foreign Keys can be addressed by manually validating the IDs before inserting or updating the data. This can be done by querying the related table to ensure that the IDs exist before saving them in the field.

// Assuming $selectedIds is an array of selected IDs
foreach ($selectedIds as $id) {
    $result = $pdo->query("SELECT id FROM related_table WHERE id = $id");
    if (!$result->fetch()) {
        // Handle error, ID does not exist in related_table
    }
}

// Insert or update the data with the selected IDs