繁体   English   中英

如何将 select 数据与多个 select 值作为 where 子句? - 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM