【问题标题】:How to send values from variables and arrays from controller to the model如何将变量和数组中的值从控制器发送到模型
【发布时间】:2020-03-17 15:34:47
【问题描述】:

我想更改下面的脚本。 下面的脚本使用查询“like”和“array”来查找数据。 我想将这 2 个变量发送到模型中,然后将它们发送回控制器进行处理。

我的控制器

    if($lewati == 0){
        $sql = "SELECT * FROM tb_fotografer WHERE spesifikasi_foto LIKE '%$kata[$i]%'";
        $result = mysqli_query($conn, $sql);
        while($row = mysqli_fetch_assoc($result)){
            // $jml_id_filter = count($id_filter);
            // $id_filter[$jml_id_filter] = $row['id'];
            $filter_ok++;
        }
    }

我的模特

    function tampil_data_spesifik($kata,$i)
    {
    return  $this->db->query('select tb_fotografer WHERE spesifikasi_foto LIKE '%$kata[$i]%'');
    }

【问题讨论】:

  • 请您对您的问题编辑更多细节,以准确解释您想要达到的目标吗?

标签: mysql codeigniter codeigniter-3


【解决方案1】:

根据 codeigniter 的官方文档,最好在模型中执行所有 db 查询,并且您无需手动键入任何数据库连接脚本。

您的控制器处理传入的请求,通常来自路由。对于 codeigniter 版本 3,您的控制器方法应该是

public function method(){

        $lewati = 0;
        $array_data = array(3, 5, 9, 4);
        $another_thing = $array_data[1] //get first item

        if($lewati === 0){
           $result = $this->model_name->method_in_model($lewati, $another_thing); //your model will accept two params
        }

        echo json_encode($result);
} 

然后你可以将你的模型更新为这样的东西

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_name extends CI_Model {

        public function method_in_model($lewati, $another_thing){
            $this->db->where('column_name', $lewati);
            $this->db->like('spesifikasi_foto LIKE', $another_thing);

             $result = $this->db->get('YOUR_TABLE_NAME');
                if(empty($result->row_array())){
                    return true;
                }else{
                    return false;
                }
        }

    }

如果它已经解决了您的问题,请告诉我

【讨论】:

    【解决方案2】:

    在你的控制器方法中

    $this->load->model('name_of_the_model_class');
    $data = $this->name_of_the_model->function_name($variable1,$variable2);
    

    在你的模型类方法中

     //do whatever your process and return the output
     return $output;
    

    【讨论】:

    • 谢谢你。最后,我只将计算转移到我的模型中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    相关资源
    最近更新 更多