G
G
green1762015-12-02 18:02:03
PHP
green176, 2015-12-02 18:02:03

How to display from db in select php?

Prompt, there is a DB, tables students and groups. I do not understand how to make a drop-down list of groups when creating a post. In the model, I created a function that pulls out a list of groups from the database, but I have no idea how to write all this into the view template.
model

function all_groups($connect){
        $query = "SELECT * FROM `students` JOIN `groups` WHERE students.sgroup = groups.gid";
        $result = mysqli_query($connect, $query);
        
        if(!$result)
            die(mysqli_error($connect));
        
        $num = mysqli_num_rows($result);
        $allg = array();
        
        for($i=0; $i<$num; $i++){
            $row = mysqli_fetch_assoc($result);
            $allg[] = $row;
        }
        
        return $allg;
    }

I don't use framework

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2015-12-02
@green176

function get_user_groups()
{
    $out = [];
    $query = "SELECT groups.gid, groups.name FROM  `groups` ";
    $result = mysqli_query($connect, $query);
    // todo тут проверки на результат
    while ($row = mysql_fetch_assoc($result)) {
         $out[$row["gid"]] = $row["name"];
    }
    return $out;
}
$groups = get_user_groups();

// Это встраиваем в форму
echo "<select name='sgroup'>";
echo "<option value="0">Выберите группу</option>";

// если мы редактируем студента и у нас уже есть группа, то при загрузке формы мы можем выбрать элемент
$student['sgroup'] = 2;
foreach($goups as $key => $value) {

    echo "<option value='" . $key . "' ". ($key ==$student['sgroup'] ? "selected" : "" ) . ">" . $value . "</option>";
}
echo "</select>";

// при submit'e формы sgroup записывай в базу пользователей

A
Alexander Wolf, 2015-12-02
@mannaro

While my personal psychic is visiting us, tell us what framework you use, show us a piece of code. In a word, give more information.

U
Uwe_Boll, 2015-12-02
@Uwe_Boll

$all_groups = all_groups($connect);
if(!is_array($all_groups){
echo 'Byada Pyachal';
}else{
foreach($all_groups as $item){
option's here
}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question