-1

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

在模型中,我检查名称是否已经存在,仅将数据插入phone_info表中。IF 名称不存在我将数据插入到user_infoandphone_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', 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);
    }
}

数据库表用户信息: 用户信息表

数据库表电话信息: phone_info 表

4

1 回答 1

0

Extend and change your model to this:

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

Explanation:

This:

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

..is not working to find database entries by name. To do this you can use codeigniters built in model functions and benefit from the MVC Pattern features, that CodeIgniter comes with.

I wrapped the actual findByName in a function so you can adapt this to other logic and use it elswehere later on. This function uses the query() method.

Read more about CodeIgniters Model Queries in the documentation.


Sidenote: mysqli_num_rows is used to iterate find results recieved by mysqli_query. This is very basic sql querying and you do not need that in a MVC-Framework like CodeIgniter. If you every appear to need write a manual sql-query, even then you should use CodeIgniters RawQuery methods.

于 2021-07-26T10:50:24.843 回答