0

Im currently using a select statement for a dropdown box to select from multiple products. On an edit form i want the select to automatically select the choice that was originally chosen which is stored in the variable $product. Im using an array to bring in all choices from the database table however can't get the array to work aswell as select the data stored in $product.

The code i've currently got is;

  $selectquery = "SELECT * FROM `loanproducts`";
  $selectresult = mysqli_query($connection, $selectquery);



  <select name="product" style="width: 150px">
    <?php while($row1 = mysqli_fetch_array($selectresult)):;?>
    <option><?php echo $row1[1];?></option>
    <?php endwhile;?>
  </select></p></div>

Im not sure if I've explained what im trying to do well enough as it is confusing me even trying to explain.

-Basically for example I have 3 choices from the array- A, B & C. -If the user goes through the form and selects B, when I then go to edit their choices I want their option to appear in the select box (B) - rather than the first choice on the array which would presumably be A

Thanks

1 Answer 1

2

I changed a little your programming style which is not very confortable to me. Anyway, the important thing here is that I create the variable $selected with two possible values : "" or "selected", depending if the current product ($row1[1]) is equal to the product selected ($product). All options but one will get "", only the selected product will get "selected" :

<select name="product" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectresult))
      { if ( $row1[1] == $product ) // IF CURRENT PRODUCT WAS SELECTED
             $selected = "selected";
        else $selected = "";
        echo "<option $selected>{$row1[1]}</option>";
      }
?>
</select></p></div>
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.