du970294 2015-08-02 09:31
浏览 38

CodeIgniter中的Mysql INSERT和SELECT

I have 3 tables a many -to-many,

BOOK

book_id | book_name | rubric | autor

RUBRIC

rubric_id | rubric_name

AUTOR

autor_id | first_name | last_name

I looking for query that select all data in one table. I insert data via form like this:

Controller

public function insert_data_to_db(){

        $form_data_book_name['book_name'] = $this->input->post('book_name');
        $form_data_autor['first_name'] = $this->input->post('first_name');
        $form_data_autor['last_name'] = $this->input->post('last_name');
        $form_data_rubric['rubric'] = $this->input->post('book_rubric');

        $proc = $this->book_model->insert_books_to_db($form_data_book_name);
        if($proc){
            echo "ok";
        }

        $proc1 = $this->book_model->insert_autors_to_db($form_data_autor);
        if($proc1){
            echo "ok";
        }

        $proc2 = $this->book_model->insert_rubric_to_db($form_data_rubric);
        if($proc2){
            echo "ok";
        }
}

MODEL

public function insert_books_to_db($form_data_book_name){
        return $this->db->insert('book',$form_data_book_name);
    }

    public function insert_autors_to_db($form_data_autor){
        return $this->db->insert('autor',$form_data_autor); 
    }

    public function insert_rubric_to_db($form_data_rubric){
        return $this->db->insert('book',$form_data_rubric); 
    }

And to select data I use query in my Model like this:

public function show_book_and_autor_name(){
        $query = $this->db->query("SELECT DISTINCT book.book_name, autor.first_name, autor.last_name, rubric.rubric_id FROM book LEFT JOIN autor ON book.autor=autor_id LEFT JOIN rubric ON book.rubric=rubric_id ORDER BY book.book_id;");
        return $query->result();
    }

How to insert in column autor | rubric some keys with relations with table AUTOR and RUBRIC? And How to select it in right way? Thank you in advance!

  • 写回答

1条回答 默认 最新

  • dqb14659 2015-08-02 17:53
    关注

    In your models you could use the function:

    $this->db->insert_id();
    

    to get the inserted ID. You could do:

    public function insert_books_to_db($form_data_book_name){
        if ( $this->db->insert('book',$form_data_book_name) )
            return $this->db->insert_id();
    }
    

    Read the CodeIgniter Documentation

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!