首页 > 解决方案 > Codeigniter foreach 循环行插入到表中

问题描述

我在前端有一个表单,我试图将值提取到隐藏的输入元素中,然后尝试插入到表中。但它不起作用,我收到未定义变量的错误,user_id_ins我正在从函数中将值提取到隐藏的输入元素中get_autocomplete

你们能帮我实现这一目标吗?

控制器

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class AddMeeting extends CI_Controller {

    public function __construct(){
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->database();
        $this->load->model('meetinginsert');
    }

    function index() {
        $this->form_validation->set_rules('organisationName', 'Organisation name', 'required');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('addmeeting');
        } else {

        $data = array(
            'organisation_name' => $this->input->post('organisationName'),
            'user_id' => $this->input->post('user_id')
        );

        $this->meetinginsert->meeting_insert($data);
        $data['message'] = 'Meeting added';
        $this->load->view('addmeeting', $data);
        }
    }

    function get_autocomplete() {
        if(isset($_GET['term'])) {
            $result = $this->meetinginsert->search_user($_GET['term']);
            if(count($result) > 0) {
                foreach($result as $row) {
                    $user_id_ins = $row->id;
                    $arr_result[] = $row->first_name . " " . $row->last_name;
                    echo json_encode($arr_result);
                }
            }
        }
    }
}
?>

看法

<input type="hidden" name="user_id" value="<?php echo $user_id_ins; ?>">

标签: phpcodeigniter

解决方案


假设它$arr_result是您输入视图的内容,错误是因为$user_id_ins不包含在视图中$arr_result,因此没有传递给视图。

$arr_result,您现在拥有的方式只是一个一维数组,其中每个元素都只是姓名和姓氏的串联。您需要传递两个参数,例如:

$arr_result[] = (user_id_ins => $user_id, fullname => $row->first_name . " " . $row->last_name);

然后,您可以通过调用$user_id_ins$fullname(或您愿意使用的任何名称)访问视图中的两个字段


推荐阅读