title: Prepopulating a select input fields in an update form
body: <p>I am creating an update form for data in my php/mysql application. To prepopulate the values of an input type="text" field in the update form from existing data, i am using this code:</p>
  
  <pre><code>&lt;label for="username"&gt;Username:&lt;/label&gt;
  &lt;input name="username" type="text" value="&lt;?php echo htmlentities($username, ENT_COMPAT, 'utf-8'); ?&gt;"&gt;
  </code></pre>
  
  <p>This code above successfully displays the existing data from the database for editing.
  However, for a select dropdown input field that dynamically creates select options as in the code below, how do I redisplay the existing selected data in an update form?</p>
  
  <pre><code>&lt;label for="user_role"&gt;User Role:&lt;/label&gt;
  &lt;select name="user_role"&gt;
     &lt;option value=""&gt;Select User Role&lt;/option&gt;
  &lt;?php
     // get results
     $query = 'SELECT userid, user_role FROM users_profile ORDER BY user_role';
     $results = $conn-&gt;query($query);
     while ($row = $results-&gt;fetch_assoc()) {?&gt;
     &lt;option value="&lt;?php echo $row['user_role']; ?&gt;"  &lt;?php if (isset($_POST['userid']) &amp;&amp;     in_array($row['user_role'], $_POST['user_role'])) {echo 'selected';
     } ?&gt;&gt;&lt;?php echo $row['user_role']; ?&gt;&lt;/option&gt;
  &lt;?php } ?&gt;
  &lt;/select&gt; 
  </code></pre>