CodeIgniter 3 代码不会将数据库中的数据添加到 2 个不同的表中user_info 和 phone_info

问题描述

问题是当我输入新名称时没有添加数据。当我输入一个已经存在的名字时,也会发生类似的事情。尽管如此,没有数据被添加数据库中。我还是 CodeIgniter 的新手,不能完全确定模型中的查询构建器是否正确。

在模型中,我检查名称是否已存在,仅将数据插入到 phone_info 表中。如果名称不存在,我将数据插入 user_infophone_info

控制器:

public function addData()
{
    $name = $this->input->post('name');
    $contact_num = $this->input->post('contact_num');
    if($name == '') {
        $result['message'] = "Please enter contact name";
    } elseif($contact_num == '') {
        $result['message'] = "Please enter contact number";
    } else {
        $result['message'] = "";
        $data = array(
            'name' => $name,'contact_num' => $contact_num
        );
        $this->m->addData($data);
    }
    echo json_encode($result);
}

型号:

public function addData($data)
{
    if(MysqLi_num_rows($data['name']) > 0) {
        $user = $this->db->get_where('user_info',array('name' => $data['name']))->result_array();
        $user_id = $user['id'];
        $phone_info = array(
            'contact_num' => $data['contact_num'],'user_id' => $user_id
        );
        $this->db->insert('phone_info',$phone_info);
    } else {
        $user_info = array(
            'name' => $data['name']
        );
        $this->db->insert('user_info',$user_info);
        $user = $this->db->get_where('user_info',$phone_info);
    }
}

DB-Table user_info:

user_info table

DB-Table phone_info:

phone_info table

解决方法

将您的模型扩展并更改为:

public function findByTitle($name)
{
    $this->db->where('name',$name);
    return $this->result();
}

public function addData($data)
{
    if(count($this->findByTitle($data['name'])) > 0) {
        //.. your code
    } else {
        //.. your code
    }
}

说明:

这个:

if(mysqli_num_rows($data['name']) > 0)

.. 无法按名称查找数据库条目。为此,您可以使用内置于模型函数中的 codeigniters,并从 CodeIgniter 附带的 MVC 模式功能中受益。

我将实际的 findByName 包装在一个函数中,以便您可以将其调整为其他逻辑并稍后在其他地方使用它。此函数使用 query() 方法。

CodeIgniters Model Queries 中阅读有关 documentation 的更多信息。


旁注: mysqli_num_rows 用于迭代 mysqli_query 收到的查找结果。这是非常基本的 sql 查询,在像 CodeIgniter 这样的 MVC 框架中不需要它。如果您似乎都需要编写手动 sql 查询,那么您应该使用 CodeIgniters RawQuery 方法。