gpt4 book ai didi

php - 如何使用 CodeIgniter 插入多个表

转载 作者:可可西里 更新时间:2023-11-01 08:31:38 25 4
gpt4 key购买 nike

我有两个彼此之间具有 (1:1) 关系的表。

customers table:
- customerID (PK)(AI)
- customerName
- phone

addresses table:
- customerID (PK&FK)
- address
- city
- zipcode

我试图在相同的 CodeIgniter View 表单中更新它们。

update_view.php

<th>Customer Name:</th>
<td><input type="text" name="customerName"/></td>
<tr>
<th>Customer Phone:</th>
<td><input type="text" name="phone"/></td>
<tr>
<th>Address:</th>
<td><input type="text" name="address"/></td>
<tr>
<th>City:</th>
<td><input type="text" name="city"/></td>
<tr>
<th>Zip Code:</th>
<td><input type="text" name="zipcode"/></td>

这是我的 Controller 代码的一部分:

    public function insert()
{
$this->load->database();
$this->load->model('my_model');
$this->my_model->insert_entry();

$custInsert=$this->my_model->get_all_customers();
$this->load->view('main_view',array('customer'=>$custInsert));
..
}

注意:到目前为止,一切都在处理一张表(客户)。

这是我的模型文件的一部分:

function insert_entry()
{
$this->customerName = $_POST['customerName'];
$this->phone = $_POST['phone'];
$this->db->insert('customers', $this); // up to here it was working

//$customerID=$db->insert_id;
$customerID=$this->db->query("SELECT MAX(customerID) FROM `customers`");
$this->customerID;
$this->address = $_POST['address'];
$this->city = $_POST['city'];
$this->zipcode = $_POST['zipcode'];
$this->db->insert('addresses', $this);
}

至于我,问题是“地址”表需要 customerID,但我没有手动插入它(auto_increment)。插入客户表后,我尝试了很多方法来获取它,但我做不到。有没有人知道不同的方式或者我应该怎么做?

最佳答案

这样做是个坏主意……当几乎同时添加新客户时,您的应用程序将如何处理?

$customerID=$this->db->query("SELECT MAX(customerID) FROM `customers`");

您应该去掉那一行并使用首选且有效的方法。如果不这样做,它可能并且将不可避免地导致您在某个时间点获取错误的客户记录并将地址与错误的客户相关联。

这是因为在(几乎足够)同时运行代码的两个客户端可能会在同一时间点遇到 MAX(),因此每个客户端都可以获得相同的值。当他们都尝试保存时,只有一个会成功,另一个会因为主键约束而失败。这种情况称为竞争条件,应加以防范。

改用这个:

 $this->db->insert_id()

还有这个:

$this->customerID;

应该是:

$this->customerID = $this->db->insert_id();

关于php - 如何使用 CodeIgniter 插入多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24792864/

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