How can I insert a value to database having an array values in my <input>
tag. I'm making online library system; this part is I'm adding a book to database sometimes a book have more than 1 author.
Now I use implode to insert but the 2 authors are sharing in 1 one column. What I want they have to be in different column when inserting to tbl_authors. I insert book details to tbl_books and for authors in tbl_authors. I've tried for each but I can only do it when displaying data when insert I have no idea
foreach($test as value)
{
'author_name' => $value[' no idea what i need to put here']
}
public function insertbooks()
{
$data=array(
'book_id' => $this->db->insert_id(),
'book_title' => $this->input->post('booktitle',true),
'section_id' => $this->input->post('section',true),
/*'book_author' => $this->input->post('bookauthor',true),*/
'book_serial' => $this->input->post('serial',true),
'book_qty' => $this->input->post('bookqty',true),
);
$sql1 = $this->db->insert('tbl_books',$data);
$author_name=implode(',', $this->input->post('bookauthor',true));
$data2=array(
'book_id' => $this->db->insert_id(),
'author_name' => $author_name
);
$sql2 = $this->db->insert('tbl_authors',$data2);
}
CodePudding user response:
You'd probably need to have each author inserted as a different row not column.
To achieve this, you should iterate authors array and make each insert separately, like:
public function insertbooks()
{
$data = array(
'book_id' => $this->db->insert_id(),
'book_title' => $this->input->post('booktitle',true),
'section_id' => $this->input->post('section',true),
'book_serial' => $this->input->post('serial',true),
'book_qty' => $this->input->post('bookqty',true),
);
$sql1 = $this->db->insert('tbl_books',$data);
$book_id = $this->db->insert_id();
foreach ($this->input->post('bookauthor',true) as $author) {
$data2=array(
'book_id' => $book_id,
'author_name' => $author
);
$sql2 = $this->db->insert('tbl_authors',$data2);
}
}
This way, you'll have separate record for each book / author relationshi.