简体   繁体   中英

how to select data with multiple select value as where clause ? - Ajax Codeigniter

I was trying to get data from a table. I use select2 multiple select on codeigniter. How to select the data on my model where category = selected values on the option ?

here is my select 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>

and here is the example of the data that I have:

<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>

I think you're asking how to select multiple items from the database when you've submitted a form using a multiple select.

IF thats a correct assumption, like this:

<form method="post" action='/admin/formproc'>
    <select multiple name='categories[]> 
        <options....>
    </select>

this will submit to your codeigniter application.

// 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) ";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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