Skip to content
Advertisement

how create sorting sql/php with parent

phpmyadmin

picture

index.php file

$id = '8';
$idr = $row['id']; echo 'id-'.$id.' : ';
 for ($i = 0; $i <= $id; $i++) {
  $sql="SELECT * FROM menu WHERE parent='$i' ";
  $result = mysqli_query($db,$sql);
  $slug = $row['slug']; echo $slug; echo '/'; 
}
if ( !empty ($id) ) { echo '-No Data-'; }

I want to show the output as shown below:

id-8 : g/h
id-6 : a/b/c/d/e/f
id-4 : a/b/c/d
id-1 : a
id-7 : g
id-10 : -No Data-

Advertisement

Answer

Do not do multiple SQL queries inside a for-loop! It’s inefficient. Form a single SQL query, instead. Something like:

$sql = "SELECT 
            parent, 
            GROUP_CONCAT(
                DISTINCT slug -> 
                ORDER BY slug ASC 
                SEPARATOR '/'
            ) as slugs
        FROM 
            menu
        WHERE 
            parent <= " . $id . "
        GROUP BY 
            parent;"

Then format the results as you wish.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement