![](/img/trans.png)
[英]How to select data with array value on where clause with ajax - codeigniter
[英]how to select data with multiple select value as where clause ? - Ajax Codeigniter
我試圖從表中獲取數據。 我在 codeigniter 上使用 select2 多個 select。 如何 select 我的 model 上的數據, where category = selected values on the option
?
這是我的 select 選項:
<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>
當您使用多個 select 提交表單時,我想您是在問如何從數據庫中 select 多個項目。
如果這是一個正確的假設,如下所示:
<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) ";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.