我是codeigniter的新手,正在尝试弄清楚如何将数据输入到与另一个相关表(客户端)中的另一行数据相关的表(电话)中。现在,我认为我需要做的是获取最近创建的客户端行ID,并将其指定为电话表行的外键字段。所以我的问题是我如何得到它,以便我可以在屏幕上回显它,以便我可以确定它可以用于其他目的。我试图将client_id的值存储到变量$ client_id中。但我收到以下php错误:
遇到PHP错误
严重性:注意
消息:未定义的变量:client_id
文件名:views / form_success.php
行号:1
为了参考目的,我包括我的代码而不更改名称,因为这不是商业项目,但应该模拟一个。 MODEL
<?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);
}
AND SUCCESS MESSAGE(form_success)
<div class="alert alert-success">Client created! User ID = <?php echo ($client_id); ?></div>
答案 0 :(得分:0)
我认为获取数据有问题:
function get_id() {
// Get id of most recently created record in client table.
$this->db->select_max('client_id');
$query = $this->db->get('client');
$data = $query->result();
/* or
foreach ($query->result() as $row)
{
echo $row->title;
}
*/
return $data;
}
答案 1 :(得分:0)
您可以使用$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);
}