dongshi7433 2017-03-23 00:50
浏览 61
已采纳

复选框并从数据库中设置其默认选中的值

I have the following database table called artist_genres. I currently have a function which finds all genre_id's by artist and echo's them in an object oriented way:

<?php
$artistgenres = Artistgenres::find_all_genres_by_artist_id($_SESSION['artist_id']);
foreach($artistgenres as $artistgenre){
  echo $artistgenre->genre_id."<br>";
}
?>

enter image description here

When the artist with id 8 logs in, and goes to this page, I would like for him to be able to update the current genre_ids associated with them.

The form data looks like:

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<div class="checkbox">
  <label><input type="checkbox" name="Genres[]" value="2">Classical</label>
</div>
<div class="checkbox">
  <label><input type="checkbox" name="Genres[]" value="3">Hiphop</label>
</div>
<div class="checkbox">
  <label><input type="checkbox" name="Genres[]" value="4">Jazz</label>
</div>
<input type="submit" name="submit" class="btn btn-primary btn-lg active" id="grad" value="Login" />
</form> 

So effectively, for the classical example, what I want to achieve is to look up and find all genre_id, see if the value 2 is in the list of genre_ids, if so change the markup to:

  <label><input type="checkbox" name="Genres[]" value="2"<? php if(somecondition = 2) {echo "checked"} ?> >Classical</label>

However, I'm having a hard time putting this into code. Can you help me out?

  • 写回答

1条回答 默认 最新

  • dscs63759 2017-03-23 01:25
    关注

    Put all of the selected genres of the user in an array:

    $selectedgenres = array();
    foreach($artistgenres as $artistgenre){
        $selectedgenres[] = $artistgenre->genre_id;
    }
    

    List all genres as checkboxes (I assume you have a separate table for all of your genres). Then use in_array() to check each genre if it is part of the selected genres by the user:

    foreach(your condition here for getting all genres){
    
    ?>    
        <div class="checkbox">
            <label><input type="checkbox" name="Genres[]" value="<?=($genreid)?>"><?=($genredesc)? <?php echo (in_array($genreid, $selectedgenres))?' checked':''; ?>></label>
        </div>
    
    <?php
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题