Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
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 записывай в базу пользователей
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question