CodeIgniter:自定义库中的insert_batch - 失败但没有返回或错误 - 如何调试?

时间:2013-10-23 14:56:08

标签: php codeigniter activerecord batch-insert

我有一个自定义CodeIgniter库,我需要运行一些数据库操作。

要访问数据库,我执行此命令,这是我在StackOverflow上学到的:

$this->CI =& get_instance();

我知道它有效,因为这个命令有效:

$drop_query = "DELETE FROM product_images WHERE product_id = " .  $this->CI->db->escape($product_id);
$this->CI->db->query($drop_query);  // Tested, this works.

但是, insert_batch 根本不起作用。没有FALSE返回,没有错误......没什么。它就死了。

    $master_insert_array = array(
        array(
            'product_id' => $product_id,
            'thumb_type' => 'original',
            'filename' => $orig_file_name
        ),
        array(
            'product_id' => $product_id,
            'thumb_type' => 'small',
            'filename' => $small_file_name
        ) // Truncating the rest of this...
    );

    error_log("update_product_image_db: Insert_Batch Coming up:");

    $batch_success = $this->CI->db->insert_batch('product_images', $master_insert_array);
    error_log("\n\n".$this->CI->db->last_query()."\n");

*编辑:事实证明我的$ product_id失败了外键约束,导致batch_insert失败。*

第二个error_log在失败后永远不会运行。剧本就要死了。

那么我如何才能让insert_batch正确地返回给我一个错误,一个错误,或者一个非平局失败的东西?

*更新:我也尝试将其放入try / catch块,但没有成功。如果它的外键约束失败,它将中止我的整个脚本。我目前认为insert_batch是一个写得不好的函数*

谢谢!

1 个答案:

答案 0 :(得分:1)

我意识到这是一个老问题,但Codeigniter仍然在第2节中遇到这个问题,所以希望这会对某人有所帮助。

无论出于何种原因,insert_batch()都不会以与标准查询相同的方式返回。通常,您可以这样做:

if(!$this->CI->db->insert('product_images', $simpleArray)
{
    error_log("\n\n".$this->CI->db->last_query()."\n");
}

但正如在原始问题中发现的那样,insert_batch在失败的查询中不会返回false。对于insert_batch(),此解决方法很好地解决了我的应用程序中的问题:

$this->CI->db->insert_batch('product_images', $master_insert_array);

if($this->CI->db->_error_message() != '')
{
    error_log("\n\n".$this->CI->db->last_query()."\n");
}