I want to insert multiple data (PHP CodeIgniter) using array. but I still find an error. The error is array is not clear
function insert(){
$hitung=count($_POST['pembicara']);
$pengisi=implode(',',$_POST['pembicara']);
$materi=implode(',',$_POST['materi']);
$alasan=implode(',',$_POST['alasan']);
$datapembicara = array(
'id_kegiatan' => $x,
'nama_pembicara' => $pengisi,
'materi' => $materi,
'alasan' => $alasan,
);
$this->m_admin_smf->add_pembicara($datapembicara);
}
when I var_dump show the result like
array (size=4)
'id_kegiatan' => int 990550
'nama_pembicara' => string '1,2' (length=9)
'materi' => string '1,2' (length=3)
'alasan' => string '1,2' (length=3)
array (size=4)
'id_kegiatan' => int 990550
'nama_pembicara' => string '1,2' (length=9)
'materi' => string '1,2' (length=3)
'alasan' => string '1,2' (length=3)
the result is should be like
array (size=4)
'id_kegiatan' => int 990550
'nama_pembicara' => string '1' (length=9)
'materi' => string '1' (length=3)
'alasan' => string '1' (length=3)
array (size=4)
'id_kegiatan' => int 990550
'nama_pembicara' => string '2' (length=9)
'materi' => string '2' (length=3)
'alasan' => string '2' (length=3)
what should I do?
How if like this? but show an error
$hitung = count($_POST['pembicara']);
$datapembicara = array();
for($i = 0; $i < $hitung; $i++) {
$datapembicara[] = array(
'id_kegiatan' => $x,
'nama_pembicara' => $_POST['pembicara'][$i],
'materi' => $_POST['materi'][$i],
'alasan' => $_POST['alasan'][$i],
);
}
$this->m_admin_smf->add_pembicara($datapembicara);
If you want them on a series of batches, then you'll have to do something other than implode
since the behavior will be different from the one you need. You can use a simple for
loop to create such array structure into series of batches:
// Controller
function insert()
{
$hitung = count($_POST['pembicara']);
$datapembicara = array();
for($i = 0; $i < $hitung; $i++) {
$datapembicara[] = array(
'id_kegiatan' => $x,
'nama_pembicara' => $_POST['pembicara'][$i],
'materi' => $_POST['materi'][$i],
'alasan' => $_POST['alasan'][$i],
);
}
var_dump($datapembicara);
$this->m_admin_smf->add_pembicara($datapembicara);
}
Sidenote: I'd suggest use input
class of codeigniter since it can handle XSS for you.
$value = $this->input->post('value', true); // add true parameter flag
Then after said array is made, you can use ->insert_batch()
of active record. It'll do the multiple insertions for you, plus, your values are automatically escaped.
// Model
public function add_pembicara($data)
{
$this->db->insert_batch($data);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With