Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting categories from database to HTML Optgroups and options in php
    primarykey
    data
    text
    <p>I am trying to get my categories from the database with their subcategories into <code>&lt;optgroup&gt;</code> and <code>&lt;option&gt;</code> tags and I want the parents to be <code>&lt;optgroup&gt;</code> tags but I can't loop through all the levels, I only get to level 2 and I can't get too far!</p> <p>This is what I got so far: </p> <pre class="lang-php prettyprint-override"><code>$con = mysql_connect($dbHost, $dbUsername, $dbPassword); if (!$con) { echo "Cannot connect to the database: " . mysql_error(); exit; } $db_selected = mysql_select_db($dbName, $con); if (!$db_selected) { echo "Can\'t use $dbName : " . mysql_error(); exit; } $query = "SELECT * FROM categories"; $result = mysql_query($query); $pidHolder = null; // To take the current parent pid in the loop $optOpen = false; // Check that optgroup tag is opened while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { if ($line['parent_id'] == 0 &amp;&amp; $line['cat_id'] == 0) continue; if ($line['parent_id'] == 0) { if ($optOpen) { echo '&lt;/optgroup&gt;'; $optOpen = false; } echo "&lt;optgroup value=" . $line['cat_name'] . "\" label=\"" . $line['cat_name'] . "\"&gt;"; $pidHolder = $line['cat_id']; $optOpen = true; continue; } else if (isset($pidHolder) &amp;&amp; $pidHolder == $line['parent_id']) { echo '&lt;option value="' . $line['cat_id'] . '"&gt;' . $line['cat_name'] . '&lt;/option&gt;\n'; continue; } } mysql_close(); </code></pre> <p>What's the problem with my code? and what do I need to loop through the rest of children?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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