Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Remember that <code>mysql_*</code> familiy of functions is now deprecated, try using PDO.</p> <p>Seems you can use a <code>JOIN</code> statement and run a single query, please try this code:</p> <pre><code>$db = new PDO('mysql:host=localhost;dbname=&lt;SOMEDB&gt;','&lt;USERNAME&gt;','PASSWORD'); $statement = $db-&gt;prepare("SELECT s.suppliers_id AS id, s.supplier_name AS name, u.unit_user_id AS user_id FROM suppliers s LEFT JOIN units_suppliers u USING suppliers_id WHERE (u.unit_user_id = :user_id OR u.unit_user_id IS NULL) GROUP BY s.supplier_name ORDER BY s.supplier_name"); if (isset($old_details['unit_user_id'])) { $user_id = $old_details['unit_user_id']; } else if (isset($_POST['old_unit_id'])) { $user_id = $_POST['unit_user_id']; } else { $user_id = 0; } $statement-&gt;execute(array( ':user_id' =&gt; $user_id )); $supliers = $statement-&gt;fetchAll(PDO::FETCH_ASSOC); foreach ($suppliers as $supplier) { ?&gt; &lt;option value="&lt;?php echo intval($supplier['id']) ?&gt;" &lt;?php echo ($supplier['user_id'] == $user_id ? 'selected="selected"' : '') ?&gt;&gt;&lt;?php echo htmlspecialchars($supplier['name']) ?&gt;&lt;/option&gt; &lt;?php } </code></pre> <p>Without PDO:</p> <pre><code>/** * Escape values that will be part of the query */ if (isset($old_details['unit_user_id'])) { $user_id = intval($old_details['unit_user_id']); } else if (isset($_POST['old_unit_id'])) { $user_id = intval($_POST['unit_user_id']); } else { $user_id = 0; } $suppliers = array(); $query = "SELECT s.suppliers_id AS id, s.supplier_name AS name, u.unit_user_id AS user_id FROM suppliers s LEFT JOIN units_suppliers u USING suppliers_id WHERE (u.unit_user_id = $user_id OR u.unit_user_id IS NULL) GROUP BY s.supplier_name ORDER BY s.supplier_name"; $result = mysql_query($query,$connection); if ($result) { while ($row = mysql_fetch_assoc($result)) { $suppliers []= $row; } mysql_free_result($result); } foreach ($suppliers as $supplier) { ?&gt; &lt;option value="&lt;?php echo intval($supplier['id']) ?&gt;" &lt;?php echo ($supplier['user_id'] == $user_id ? 'selected="selected"' : '') ?&gt;&gt;&lt;?php echo htmlspecialchars($supplier['name']) ?&gt;&lt;/option&gt; &lt;?php } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload