Codeigniter Database Insert Failure

有些话、适合烂在心里 提交于 2019-12-21 09:35:03

问题


Currently in my controller, when adding new data, I validate the inputs, and if there are any problems it lets a user known, otherwise it passes the data to the model to insert to the database

How do I now go about checking the insert statement worked correctly in the model, and let a user known if it did not.

Does an insert statement like below, return true or false, which can then be returned to the controller?

$this->db->insert('Faviroute_Addresses', $address_data);

Thanks for any help


回答1:


You can use

if($this->db->insert('Faviroute_Addresses', $address_data))
{
    // Code here after successful insert
    return true;   // to the controller
}

Or you can use

$this->db->insert('Faviroute_Addresses', $address_data);
if($this->db->affected_rows() > 0)
{
    // Code here after successful insert
    return true; // to the controller
}



回答2:


Personally I'd avoid using the

$this->db->affected_rows()

method for an insert. SQLServer doesn't return a value for an insert, so taking the return value from

$this->db->insert(...)

would be more reliable. I'd reserve affected_rows for checking "UPDATE"s :)

UPDATE:

The same thing applies for

$this->db->delete()

The affected_rows() function doesn't work in SQL Server on a delete...



来源:https://stackoverflow.com/questions/10015910/codeigniter-database-insert-failure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!