php - 如何将 SQL INSERT INTO SELECT 与 codeigniter 一起使用
问题描述
如何在 CodeIgniter 中使用 SQL 插入到 select 中。
模型...
public function history($book_id)
{
$query = $this->db->query('INSERT orders (book_id, title)
SELECT book_id, book_title
FROM books
WHERE book_id = \'$book_id\'');
return true;
}
解决方案
首先从books
表中获取所有书籍,然后根据您的插入顺序$book_id
例子:
public function history($book_id)
{
$this->db->select('book_id, book_title');
$this->db->from('books');
$this->db->where('book_id', $book_id);
$query = $this->db->get();
if ( $query->num_rows() > 0 ) // if result found
{
$row = $query->result_array(); // get result in an array format
$data = array();
foreach($row as $values){
$data = array(
'book_id' => $values['book_id'],
'title' => $values['book_title']
);
$this->db->insert('orders', $data); // insert in order table
}
return true;
}
else{
return false;
}
}