从codeigniter中的复选框中选择动态表列的SQL查询?

时间:2015-08-05 03:28:04

标签: sql codeigniter dynamic checkbox

我正在尝试根据codeigniter中的复选框选择从数据库中检索列。但我不知道怎么做?

例如,数据库表中有一列成员:

|  ID   | Name   | Gender   | Status  |
---------------------------------------
|  1    | Anne   |  F       | Member  |
|  2    | Brown  |  M       | Member  |
|  3    | Carl   |  M       | Member  |

<小时/> 然后在data.php视图中有复选框,以选择要显示的列

<?php echo form_open(data/getData);?>
<label class="col-md-4" for="parameter">Parameter</label>
<div class="col-md-6">
 <input type="checkbox" id="parameter" value="name"> Name <br>
 <input type="checkbox" id="parameter" value="gender"> Gender <br>
 <input type="checkbox" id="parameter" value="status"> status <br>
</div>
<input type="submit" class="btn btn-md btn-info" value="Process" />
<?php echo form_close();?>

<div class="well">
   <table class="table table-bordered table-hover" cellspacing="0" width="100%">
     <thead>
       <tr class="info">
         <th>ID</th>
         <th></th>
         <th></th>
         <th></th>
       </tr>
     </thead>
     <tbody>
       <?php foreach($query as $d): ?>
        <tr> 
         <td><?php echo $d['ID'];?></td>
         <td><?php echo $d[''];?></td>
         <td><?php echo $d[''];?></td>
         <td><?php echo $d[''];?></td>
        </tr>
       <?php endforeach ?>
     </tbody>
   </table>
 </div>

如何动态地从复选框中检索列名?

Data_model.php:

function getData(){
  //I don't know how to get the dynamic column select from the view to the select query

  $this->db->select(?);
  $this->db->from('member');
  $query = $this->db->get();
  return $query->result();
}

有人帮我这个吗?

1 个答案:

答案 0 :(得分:3)

尝试这种简单的方法,使用名称属性param[]和数组

进行POST / GET
<input type="checkbox" id="parameter" name="param[]" value="name"> Name <br>
 <input type="checkbox" id="parameter" name="param[]" value="gender"> Gender <br>
 <input type="checkbox" id="parameter" name="param[]" value="status"> status <br>
PHP中的

(假设发布值)

$param = $this->input->post('param');

//if no param get all columns
if(empty($param)){
 $param = '*';
}else{

  //if array value is more than 1 use implode else just take the 1st array
  $param = (count($param) > 1 ) ? implode(',', $param) : $param[0]; //make a single string and concatenate them with , 
}
example output: name,status

然后在模型中使用$ param,例如$this->db->select("$param");