2

Im trying to make an update form. In this update form is a dropdown list that is populated with value's from an mysql table. Now i got the expected values but i cannot get the right value to be selected (the one that belongs to the ID).

For example:

  1. co_id = the record for contacts, thats the one im updating.
  2. co_cs_id = the id of the company that belongs to the co_id, this is should be the selected value.

I got the following code:

echo "<td style width='30%'><select type='text' data-live-search='true' required data-live-search-style='startsWith' class='selectpicker form-control' name='co_cs_id' value='$contacts->co_cs_id'>";
$query = "  SELECT cs_id, cs_name
            FROM customers_suppliers            
            WHERE cs_status=0 
            ORDER BY cs_name";


            $stmt = $db->prepare($query);
            $stmt->execute();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    extract($row);
    echo "<option value='{$cs_id}'>{$cs_name}</option>";
}
echo "</select>";

This an example record: Record information before update form

Update form with wrong company value

You can see that the company value is not the same.

9
  • The <select>-element does not have an value attribute. Not sure if that would screw it up though. What does your generated HTML look like? Commented Mar 9, 2020 at 20:15
  • have you tried removing the value from your select element. So far I can not see anything that is causing this to be wrong. Commented Mar 9, 2020 at 20:17
  • The page looks as follow: imgur.com/a/XwuZbSj The thing is that now test1 is selected while based on this record it should be test 3. Commented Mar 9, 2020 at 20:19
  • @C.Jacobs I am unable to view that link Commented Mar 9, 2020 at 20:21
  • How about this one? imgur.com/4m7isyc Commented Mar 9, 2020 at 20:22

1 Answer 1

2

you can use selected attribute

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    extract($row);
    if($cs_id == $co_cs_id) {
        echo "<option value='{$cs_id}' selected>{$cs_name}</option>";
    } else {
        echo "<option value='{$cs_id}'>{$cs_name}</option>";
    } 
}

or in one line

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    extract($row);
    echo "<option value='{$cs_id}'".(($cs_id == $co_cs_id) ? "selected" : "").">{$cs_name}</option>";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.