Multiple Checkbox Input in CodeIgniter

Sometimes we need to insert multiple checkbox value to our database. We also need to combine our input values with our ID to get some table relations. For example, we will auto cluster students to class A and B. So, we need to have an input form there show students username, and optional value for class A or B.

If we press the submit button, it will process and save id_siswa and class to our new table. This table just for new relations. You know, if there is mandatori relations, so we need new table for save the relations.

Here is my simple code,

The controller

<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Welcome extends CI_Controller { public function index() { $this->load->view('welcome_message');
	}


	public function proses_kelas(){

	$id_siswa = $this->input->post('id_siswa');
	$kelas = $this->input->post('kelas[]');	

	$jml_siswa = count($id_siswa);
	for ($i=0;$i<$jml_siswa;$i++){ $data = array('id_siswa' => $id_siswa[$i], 'kelas' => $kelas[$i] );
$this->db->insert('kelas_siswa',$data);
	}
	echo "sukses";
	}
}

The view

<!DOCTYPE html>
<html>
<head>
	<title>Multiple checkbox</title>
</head>
<body>

<form action="http://localhost:8080/multiplecheckbox/index.php/welcome/proses_kelas" method="post">
<table border="1">
	<th>
		<tr>
			<td>Nama</td>
			<td>Kelas</td>
		</tr>
	</th>
	<tbody>
<?php 
$ambil_siswa = $this->db->get('siswa')->result();
foreach ($ambil_siswa as $key) {

?>
		<tr>
			<td>

			<input type="hidden" name="id_siswa[]" value="<?=$key->id?>">
			<?=$key->nama?></td>
			<td>
				<input type="checkbox" name="kelas[]" value="A"> A
				<input type="checkbox" name="kelas[]" value="B"> B
			</td>
		</tr>
<?php } ?>
	</tbody>
</table>
<button type="submit">Proses</button>
</form>
</body>
</html>

I didn’t model file, because in this case, I pull student data from view. Its just for example case study, you can implement this code to your case.

Regrads, Sutriman



0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Richi Praudian
Richi Praudian
4 years ago

makasi tutorialnya mas… salam dari mahasiswa jurusan teknik informatika uin suska riau

Firman Hamid
Firman Hamid
3 years ago

kalo untuk update dan kondisi where nya lebih dari 1 primary key gimana ya om


2
0
Would love your thoughts, please comment.x
()
x