php Code Igniter 在插入数据时捕获错误(Active Record)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8202547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:08:47  来源:igfitidea点击:

Code Igniter catch errors on inserting data (Active Record)

phpdatabaseactiverecorderror-handlingcodeigniter-2

提问by lodhb

I am inserting data into my database using the following code:

我使用以下代码将数据插入到我的数据库中:

$this->db->set('event_id', $event_id);
...
$this->db->set('creator_id', $creator_id);

$this->db->insert('event');

How can I make sure the process was successful and show the user a confirmation message, else an error message?

如何确保该过程成功并向用户显示确认消息,否则显示错误消息?

回答by Damien Pirsy

Uhm, IIRC the method returns true if succesful, so you could go with a simple

嗯,如果成功,IIRC 方法返回 true,所以你可以用一个简单的

if($this->db->insert('event'))
{
  echo 'Row succesfully inserted!';
}

Otherwise, you might always count the affected rows:

否则,您可能总是计算受影响的行数

//....
$this->db->insert('event');
if($this->db->affected_rows() > 0)
{
  echo 'row succesfully inserted';
}

UPDATEafter comment:

评论后更新

I believe your three insert_batch() are on three different tables, so a check should be down on each one. Anyway, what's puzzling me is the reason behin this check..Query don't fail randomly: possibily they should neverfail and when they do you'll know through errors (logged or dislayed).

我相信您的三个 insert_batch() 位于三个不同的表上,因此应该对每个表进行检查。总之,什么是我百思不得其解的原因behin这check..Query不要随意失败:possibily他们应该永远不会失败,当他们这样做,你就会知道通过错误(记录或dislayed)。

回答by TV-C-15

"If you need to get the last error that has occurred, the error() method will return an array containing its code and message." https://www.codeigniter.com/userguide3/database/queries.html

“如果您需要获取发生的最后一个错误,error() 方法将返回一个包含其代码和消息的数组。” https://www.codeigniter.com/userguide3/database/queries.html

$insert = $this->db->insert('event');

             if(!$insert){

                $error = $this->db->error(); // Has keys 'code' and 'message'
                echo "<BR><BR>";
                print_r($error);
                echo "<BR><BR>";
            }

            echo "Error contact the database admin.";
            die();

        }else{

            echo "SUCCESSFULLY INSERTED ITEM";
            return TRUE;
        }