gpt4 book ai didi

php - 使用 Codeigniter 将最后插入的记录 id 插入到另一个表中的数组中

转载 作者:行者123 更新时间:2023-11-29 16:36:15 25 4
gpt4 key购买 nike

所以我有两个表,一个称为患者,另一个称为测试,测试表有患者 ID,我有一个名为添加患者的页面,其中包含用于添加新患者信息的字段和用于添加测试信息并上传所有内容的其他字段将数据放入一个查询中的两个表中,测试字段可以通过ajax复制,这样我就可以向同一患者添加多个测试,现在我想同时将多个测试添加到测试表中,我设法这样做,但情况是我无法将病人 ID 添加到测试表中,我想在该页面中添加新病人时向我添加的所有测试多次添加相同的病人 ID,我是 Codeigniter 的新手! this is the adding page

患者区域和测试区域

<input type="text" name="patientname" />
<input type="text" name="address" />

<input type="text" name="testname[]"/>
<input type="text" name="price[]" />

这是我的 Controller

public function testbby
{
$this->load->model("khmodel", "Khmodel");

// patient main info
$patient_input_data = array();
$patient_input_data['patientname'] = $this->input->post('patientname');
$patient_input_data['address'] = $this->input->post('address');

//test data
$testname = $this->input->post('testname[]');
$price = $this->input->post('price[]');

$test_input_data = array();
for ($i = 0; $i < count($testname); $i ++ )
{
$test_input_data[$i] = array(
'testname' => $testname[$i],
'price' => $price[$i],
);
}
$this->Khmodel->insert_bby($patient_input_data, $test_input_data);

redirect('main/dashboard');
}

这是我的模型

public function insert_bby($patient, $test)
{
$this->db->insert('patients', $patient);
$patient_id = $this->db->insert_id();

// i used this and it worked but only while adding one test , s
//once it's gonna be an array i dunno what to do with the id !
//$test['refpatient']=$patient_id;
$this->db->insert_batch('tests', $test);

return $insert_id = $this->db->insert_id();
}

最佳答案

首先,您不需要这个。

$patient_input_data = array();

因为当你打电话

$patient_input_data['patientname'] = $this->input->post('patientname');

将创建数组 $patent_input_data。有时您可能想确保有一个数组,即使它是空的。但这不是其中之一。

对于数组输入值,即testname[],通过去掉名称末尾的括号来获取数据。像这样。

//test data
$testname = $this->input->post('testname'); //instead of post('testname[]')
$price = $this->input->post('price');

变量 $testname$price 将是数组,其中包含表单上每个字段的项目。

在我看来,这两个输入是必需的,因此您应该添加代码来检查情况是否如此。 Form Validation class非常适合此目的。

数组 $test_input_data 是您希望该数组存在的情况 - 即使它是空的。在向数组添加项目时,您不必显式设置索引值,即 $test_input_data[$i] = array(... 因为 $ test_input_data[] = array(... 可以正常工作,但无论如何都没有坏处。

关于模型。第一部分很好。对于第二个,您需要创建包含从第一次插入中获得的患者 ID 的数组,并将该值添加到 $tests 参数中的每个子数组中。模型就变成这样了。

public function insert_bby($patient, $tests)
{
$this->db->insert('patients', $patient);
$patient_id = $this->db->insert_id();
// add the patient id key/value to each sub-array in $tests
foreach ($tests as $test)
{
$test['patient id'] = $patient_id;
}
// will return the number of rows inserted or FALSE on failure
return $this->db->insert_batch('tests', $tests);
}

关于php - 使用 Codeigniter 将最后插入的记录 id 插入到另一个表中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53585653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com