簡體   English   中英

如何在Codeigniter中使用選擇活動記錄來插入記錄

[英]How to insert records using select active records in codeigniter

我發現一些與此問題相同的問題,但是我似乎找不到自己的代碼的正確答案。 所以我要發布我的問題。

我的代碼無法正常工作並發布錯誤。 例如“ stdClass無法轉換為字符串”或關於數組的問題。

這是我的模型代碼

$this->db->select("*");
$this->db->from("table1");
$query = $this->db->get();
$this->db->insert("table2", $query->result());

這是行不通的。

現在,當我使用print_r($ query)時,結果是這樣的。

CI_DB_mysql_result Object ( [conn_id] => Resource id #30 [result_id] => Resource id #40 [result_array] => Array ( ) [result_object] => Array ( ) [custom_result_object] => Array ( ) [current_row] => 0 [num_rows] => 5 [row_data] => )

我懷疑$query作為對象回來了。

請嘗試以下方法之一,用$query->result()代替最后一行:

$this->db->insert("table2", $query->row());
//or
$this->db->insert("table2", $query->result_array());

嘗試這個:

如果select('*') ,它將返回許多行,因此不建議使用insert()因為insert僅處理ONE ROW

嘗試使用insert_batch()

$this->db->insert_batch("table2", $query->result());
//or
$this->db->insert_batch("table2", $query->result_array());

如果需要使用insert() ,則必須在第一個查詢中添加一個limit(1)

或者,如果它返回很多行,則必須捕獲您的查詢

$numrows = $query->num_rows(); 
if($numrows == 1)
{
  $this->db->insert("table2", $query->row());
}elseif($numrows > 1){
  $this->db->insert_batch("table2", $query->result_array());
}

如果您要實現的只是在兩個表之間復制數據,則應嘗試以下查詢

INSERT INTO to_table (field1,field2) (SELECT field1,field2 FROM from_table);

這在許多方面都更加有效。 它在單個查詢中產生結果。 沒有將數據傳入或發送自應用程序,從而帶來了巨大的速度優勢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM