rainbyte 发表于 2015-8-5 17:12:43

如何判断数据库写失败

$this->db->insert_batch('tablename', $datarray);
像这样批量插入数据,如果成功的话会返回插入成功的记录数.
我原意是如果插入失败就捕获失败信息,然后用log_message记录在日志里,而不是输出到页面.

问题1:如果插入失败会返回什么?
问题2:要怎样才可以抑制CI在页面输出数据库操作失败的错误信息?

谢谢.

aneasystone 发表于 2015-8-5 21:01:01

insert_batch 方法如果失败的话,会根据数据库配置文件中的 db_debug 参数来决定是显示错误信息还是返回 FALSE,如果 db_debug 设置为 TRUE,会显示出数据库出错信息,并终止脚本,如果设置为 FALSE ,就会只返回 FALSE,PHP 还会继续执行下去

rainbyte 发表于 2015-8-6 14:08:15

aneasystone 发表于 2015-8-5 21:01
insert_batch 方法如果失败的话,会根据数据库配置文件中的 db_debug 参数来决定是显示错误信息还是返回 FA ...

谢谢.确实是通过数据库配置文件config/database.php的"['db_debug'] TRUE/FALSE - Whether database errors should be displayed."来控制是否输出错误.不过我观察到的是如果insert_batch插入失败返回的是-1而不是false.

aneasystone 发表于 2015-8-6 21:22:59

rainbyte 发表于 2015-8-6 14:08
谢谢.确实是通过数据库配置文件config/database.php的"['db_debug'] TRUE/FALSE - Whether database erro ...

我不确定 CI 老的版本是不是返回 -1 或者你的版本有什么不同,但是 CI 3.0 和 2.2 都是返回 FALSE 的

rainbyte 发表于 2015-8-6 23:55:32

aneasystone 发表于 2015-8-6 21:22
我不确定 CI 老的版本是不是返回 -1 或者你的版本有什么不同,但是 CI 3.0 和 2.2 都是返回 FALSE 的 ...

嗯。你是对的。确实是FALSE。{:soso_e100:}在system/database/DB_query_builder.php中

        /**
       * Insert_Batch
       *
       * Compiles batch insert strings and runs the queries
       *
       * @param        string        $table        Table to insert into
       * @param        array        $set         An associative array of insert values
       * @param        bool        $escape        Whether to escape values and identifiers
       * @return        int        Number of rows inserted or FALSE on failure
       */
        public function insert_batch($table = '', $set = NULL, $escape = NULL)
        {
                if ($set !== NULL)
                {
                        $this->set_insert_batch($set, '', $escape);
                }

                if (count($this->qb_set) === 0)
                {
                        // No valid data array. Folds in cases where keys and values did not match up
                        return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
                }

                if ($table === '')
                {
                        if ( ! isset($this->qb_from))
                        {
                                return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
                        }

                        $table = $this->qb_from;
                }

                // Batch this baby
                $affected_rows = 0;
                for ($i = 0, $total = count($this->qb_set); $i < $total; $i += 100)
                {
                        $this->query($this->_insert_batch($this->protect_identifiers($table, TRUE, $escape, FALSE), $this->qb_keys, array_slice($this->qb_set, $i, 100)));
                        $affected_rows += $this->affected_rows();
                }

                $this->_reset_write();
                return $affected_rows;
        }






页: [1]
查看完整版本: 如何判断数据库写失败