问题描述
我试图从表中获取数据。我在 codeigniter 上使用 select2 多选。如何在我的模型 where category = selected values on the option
上选择数据?
这是我的选择:
<select name="categories[]" id="selectCategory" class="js-example-basic-multiple selectCategory" style="width: 300px;" multiple="multiple">
<option value="">All Categories</option>
<?PHP foreach ($category as $cat) {
//option value = id of category
echo '<option value="' . $cat['id'] . '">' . $cat['category'] . '</option>';
} ?>
</select>
这是我拥有的数据示例:
<table>
<thead>
<tr>
<th>Id</th>
<th>Category</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>Food</td>
<td>Pizza</td>
</tr>
<tr>
<td>3</td>
<td>Food</td>
<td>Burger</td>
</tr>
<tr>
<td>4</td>
<td>Drink</td>
<td>mineral Water</td>
</tr>
<tr>
<td>5</td>
<td>Drink</td>
<td>Tea</td>
</tr>
<tr>
<td>6</td>
<td>Snack</td>
<td>Apple Pie</td>
</tr>
</tbody>
</table>
解决方法
我想您是在问,当您使用多选提交表单时,如何从数据库中选择多个项目。
如果这是一个正确的假设,就像这样:
<form method="post" action='/admin/formproc'>
<select multiple name='categories[]>
<options....>
</select>
这将提交给您的 codeigniter 应用程序。
// Admin.php controller
function formproc() {
// CodeIgniter 4
$db = db_connect();
$categories = $this->request->getPost('categories'); // is an array
$sql = "SELECT * FROM categories WHERE id IN ? ";
$result = $db->query($sql,[$categories]);
// CodeIgniter 3
$categories = $this->input->post('categories'); // is an array
$sql = "SELECT * FROM categories WHERE id IN ? ";
$result = $this->db->query($sql,[$categories]);
}
// Here's how I'd write the SQL without codeignigter or query binding
$cats = $_POST['categories']; //comes in as an array;
$cats =implode(",",$cats);
$sql = "SELECT * FROM categories WHERE id IN ($cats) ";