如何使用CodeIgniter插入多个表

时间:2014-07-17 00:08:52

标签: php mysql sql codeigniter

我有两张桌子彼此之间有(1:1)的关系。

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

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

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

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>

这是我的控制器代码的一部分:

    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);
}

至于我,问题是'address'表需要customerID,但我不会手动插入(auto_increment)。插入到客户表后我尝试了很多方法来获取它,但我不能这样做。是否有人知道不同的方式或我应该以这种方式做什么?

2 个答案:

答案 0 :(得分:4)

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

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

你应该摆脱那条线,并使用首选和有效的方法。如果不这样做,它可能并且将不可避免地导致您在某个时间点为客户提取错误的记录并将地址与错误的客户相关联。

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

请改用:

 $this->db->insert_id()

也是这样:

$this->customerID;

应该是:

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

答案 1 :(得分:-2)

实现您想要的更简洁的方法是使用数组而不是$this。您将获得所需的所有信息,仅此而已。你的$this对象中有很多东西比你不需要的东西。

控制器

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

    $data_user = array(
      'customerName' => $this->input->post('customerName'),
      'phone'        => $this->input->post('phone')
    );

    $data_address = array(
      'address'    => $this->input->post('address'),
      'city'       => $this->input->post('city'),
      'zipcode'    => $this->input->post('zipcode')
    );    

    $this->my_model->insert_entry($data_user, $data_address);

    [...]
}

模型

function insert_entry($data_user, $data_address) {

    $this->db->insert('customers', $data_user);

    $data_address['customerID'] = $this->db->insert_id();

    $this->db->insert('addresses', $data_address);
}

在获得$_POST变量时,最好使用Input Class of Codeigniter。只需使用以下内容:

$this->input->post('VAR_NAME')代替$_POST['VAR_NAME']

相关问题