我是Codeigniter的新手,正在尝试弄清楚如何将数据输入到与另一个相关表(客户端)中的另一行数据相关的表(电话)中。现在,我认为我需要做的是获取最近创建的客户行的ID,并将其分配为电话表行的外键字段。所以我要问的问题是如何获得它,以便可以在屏幕上回显它,从而确保可以将其用于其他目的。我正在尝试将client_id的值存储到变量$ client_id中。但我收到以下php错误:
遇到PHP错误
严重程度:注意
消息:未定义的变量:client_id
文件名:views / form_success.php
行号:1
出于参考目的,我在不更改名称的情况下包括了我的代码,因为这不是商业项目,但应该模拟一个。模型
<?php
class insert_client extends CI_Model {
function __construct() {
parent::__construct();
}
function form_insert($client_data) {
// Insert Data into client table
$this->db->insert('client', $client_data);
}
function get_id() {
// Get id of most recently created record in client table.
$this->db->select_max('client_id');
$data = $this->db->get('client');
return $data;
}
}
控制器部分(请注意,模型已在代码中的函数之前加载)
if ($this->form_validation->run() == FALSE) {
$this->load->view('form_start');
$this->load->view('client_form');
$this->load->view('submit');
} else {
//CLIENT DATA
$client_data = array (
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'address' => $this->input->post('address'),
'apt_or_suite_number' => $this->input->post('apt_or_suite_number'),
'zip_code' => $this->input->post('zip_code'),
'state' => $this->input->post('state'),
'email' => $this->input->post('email'),
);
// Get ID
$client_id = $this->insert_client->get_id();
// Transfer to models and store in database
$this->insert_client->form_insert($client_data);
// Load Success View
$this->load->view('form_success', $client_id);
}
和成功消息(form_success)
<div class="alert alert-success">Client created! User ID = <?php echo ($client_id); ?></div>
您可以使用$ this-> db-> insert_id()函数。
模型:
function form_insert($client_data) {
// Insert Data into client table
$this->db->trans_start();
$this->db->insert('client', $client_data);
$insert_id = $this->db->insert_id();
$this->db->trans_complete();
return $insert_id;
}
控制器:
if ($this->form_validation->run() == FALSE) {
$this->load->view('form_start');
$this->load->view('client_form');
$this->load->view('submit');
} else {
//CLIENT DATA
$client_data = array (
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'address' => $this->input->post('address'),
'apt_or_suite_number' => $this->input->post('apt_or_suite_number'),
'zip_code' => $this->input->post('zip_code'),
'state' => $this->input->post('state'),
'email' => $this->input->post('email'),
);
// Transfer to models and store in database and get last inserted id
$client_id = $this->insert_client->form_insert($client_data);
// Load Success View
$this->load->view('form_success', $client_id);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句