D
D
Dmitry Alexandrov2018-03-10 16:49:09
PHP
Dmitry Alexandrov, 2018-03-10 16:49:09

How to get a category tree into a drop-down list from a database, as in the example?

Good day to all. Connecting to DB

//*---------------* Поключение к Базе данных *---------------//


 require_once 'config.php'; // подключаем скрипт
  // Подключение к базе данных MySQL.
  @$on_link = mysqli_connect($db_host, $db_user, $db_pass);
  if (!$on_link) {
  echo "Ошибка соединения с сервером MySQL!";
  exit;
  }
// изменение набора символов на utf8
  mysqli_set_charset($on_link, "utf8");
// Выбираем БД для работы в MySQL.

   $db_base_ref =  'ggggfffffgggg';
  @$db_select = mysqli_select_db ($on_link, $db_base_ref);
    if (!$db_select) {
    echo "Не удалось выбрать БД MySQL.";
    exit;
    }

Here is the complete list of categories:
<?
 // Делаем выборку из таблицы.
  $sql_cat = "SELECT * FROM `cat`";

  $result_select = mysqli_query($on_link, $sql_cat);

    echo "<select class='row-item-2' name = 'cat'>";

    echo "<option value='0'>Категория</option>";

        while($object = mysqli_fetch_object($result_select)){

            echo "<option value = '$object->id' > $object->name </option>";
        }
    echo "</select>";

?>

Can you please tell me how to get the category tree in the drop-down list as in the example below?
5aa3e1d66d129145259239.gif
Category table cat consists of id, name and parent

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2018-03-10
@sidni

Your code is not very clear, the image shows something wrong
when displaying a category, everything is correct, a request is made to display all categories, a select is generated (in your case, most likely, you need to select those with parent_id = 0)
the remaining selects are empty
after the user has selected a category, ajax is sent request to the server with the id of the selected category and generate data (json) for the second select where parent_id = what the user passed and display the second select and so on

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question