Kategori Random

Membuat Polling Website dengan CodeIgniter MySQL

Posted : 07 Mei 2015 | 06:04:48 , Dibaca 7157 kali

Seperti kita ketahui bahwa polling pada sebuah website berguna untuk melihat bagaimana respons dari user yang telah berkunjung ke website kita. Pada prinsipnya polling berisi sebuah pertanyaan dan kemudian ada beberapa jawaban pilihan dari pertanyaan tersebut. Kemudian setiap vote yang dilakukan oleh user pengunjung maka akan tersimpan pada sebuah file text maupun database dan kemudian kita tampilkan berupa diagram grafik maupun hanya data.

Pada kesempatan ini saya akan berbagi mengenai polling tersebut, dimana saya menggunakan framework codeigniter dan disimpan dalam database mysql.

 

Perlengkapan

1. Framework CodeIgniter => dalam hal ini saya gunakan 3.0.0
2. JQuery (jQuery v1.10.2)
3. HighCharts JS sebagai tampilan grafik hasilnya (Highcharts JS v4.0.3)

 

Database

Rancang terlebih dahulu untuk Databasenya karna pada kasus ini kita akan menyimpannya pada tabel mysql buat seperti berikut :

CREATE TABLE `t_polling` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `question` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `answer1` varchar(100) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `answer2` varchar(100) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `answer3` varchar(100) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `answer4` varchar(100) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `vote1` int(10) NOT NULL,
  `vote2` int(10) NOT NULL,
  `vote3` int(10) NOT NULL,
  `vote4` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1

kemudian isikan datatanya sebagai berikut

insert into `t_polling` (`id`, `question`, `answer1`, `answer2`, `answer3`, `answer4`, `vote1`, `vote2`, `vote3`, `vote4`) values('1','Bagaimana Tampilan Website ini?','Sangat Puas','Puas','Biasa','Kurang Puas','1','1','1','0');

 

Rancangan

Kemudian buat controllernya beri nama polling.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
ob_start();

class Polling extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('mgeneral'); //load model yg berada di folder model
        $this->load->helper(array('url')); //load helper url dan cookie
    }

    //tampilan utama polling
	public function index()
    {
        $table ='t_polling';
		$surat = "";
        $tahun = date('Y');
		$ar_data = array('id' => '1');
		$sql1 = $this->mgeneral->getbydata($table,$ar_data);
	    
		#$surat .= $sql1->num_rows().",";
        $data['grafik'] = $surat;
		
        $data['title']  = 'Polling';
        $data['description']    = '';
        $data['keyword']   = '';
        $data['judul']   = 'Polling';

        $this->load->view('vpolling',$data);
    }
	
	//menyimpan vote
	public function save() 
	{
        $vote = $this->input->post('vote');
        $ip = $_SERVER['REMOTE_ADDR'];
        
        $sessions=$this->session->userdata('polix');
        
		//cek session 
		if(empty($sessions)){ 
			$sip = $this->session->set_userdata('polix',"polling");
			//menyimpan session identitas user, agar tidak bisa dua kali vote 
			
			//query menambah vote dengan update vote ditambah 1
			$a = $this->db->query("UPDATE t_polling SET vote{$vote} = vote{$vote} + 1");
			
			//jika vote berhasil maka beri pesan berhasil
			$this->session->set_flashdata("pesan", "<div class=\"col-md-12\"><div class=\"alert alert-success\" id=\"alert\">Terimakasih atas vote anda !!</div></div>");
        }else{
			//jika sudah pernah vote maka akan muncul pesan
			$this->session->set_flashdata("pesan", "<div class=\"col-md-12\"><div class=\"alert alert-success\" id=\"alert\">Anda sudah pernah vote !!</div></div>");          
        }

        //tampil halaman
        redirect("polling/detail");
	}
	
	//fungsi detail polling
    function detail()
	{
		$table = 't_polling';
		$ar_data = array('id' => '1');
		$data['rpolling'] = $this->mgeneral->getbydata($table,$ar_data);
		
        $data['title']  = 'Grafik Polling';
        $data['description']    = '';
        $data['keyword']   = '';
        $data['judul']   = 'Polling';
		
        $this->load->view('dpolling',$data);
	}
	
	//mereset poling agar bisa divote kembali
	public function resetsession() 
	{
		$array_val = array('polix' => '');
		$this->session->unset_userdata($array_val);
			
		$this->session->set_flashdata("pesan", "<div class=\"col-md-12\"><div class=\"alert alert-danger\" id=\"alert\">Polling berhasil di reset !!</div></div>");
		redirect('polling');
	}
}

pada model buat sebuah model dan beri nama mgeneral.php buat seperti ini

<?php  
 class Mgeneral extends CI_Model {      
     public function __construct() {  
     parent::__construct();      
   }  

   function insert_data($table,$data) {  
     $this->db->insert($table, $data);  
   }
   
   function update_data($table,$data,$key) {  
     $this->db->where($key);  
     $this->db->update($table, $data);  
   }
   
   function delete_data($table,$where=0) {  
     if($where != 0) {  
       foreach($where as $key=>$val){  
         $this->db->where($key, $val);  
       }    
     }  
     $this->db->delete($table);  
   }
   
   function getbydata($table, $where) {  
     $this->db->from($table);
     $this->db->where($where);  
     $query = $this->db->get();  
      
     return $query->row();  
   }
   
   function getalldata($table) {  
     $this->db->select('*');  
     $this->db->from($table);     
     $query = $this->db->get();          
     return $query->result();  
    }
}  

Kemudian untuk tampilan views ada dua buah vpolling.php untuk tampilan utama dan dpolling.php untuk grafiknya

vpolling.php

<? $this->load->view('iheader');?>
<div class="container">

<div class="panel panel-default">
  <div class="panel-heading"><b>Polling Website</b></div>
  <div class="panel-body">
  <div id="divResult" style="font-size:10px; color: green; font-weight:bold"></div>
<form action="<?=base_url()?>polling/save" method="post" id="formVote">
 <?
	$query = $this->db->query('SELECT question,answer1,answer2,answer3,answer4 FROM t_polling')->row();
	echo $query->question;

	// tampilkan pilihan dengan format radiobutton (hanya 1 pilihan)
	echo '<br /><input type=radio name=vote value=1> '.$query->answer1;
	echo '<br /><input type=radio name=vote value=2> '.$query->answer2;
	echo '<br /><input type=radio name=vote value=3> '.$query->answer3;
	echo '<br /><input type=radio name=vote value=4> '.$query->answer4;
	echo '<br /><input type=submit name=xvote value="Vote Now">';
 ?>
</form>

<a href="<?=base_url()?>polling/detail">Lihat hasil poling</a>
</div>
</div>
</div>
<? $this->load->view('ifooter');?>

dpolling.php

<? $this->load->view('iheader');?>
<div class="container">
<div class="panel panel-default">
  <div class="panel-heading"><b>Grafik Polling Website</b></div>
  <div class="panel-body">
 <?=$this->session->flashdata('pesan')?>
<?
 $pertanyaan =$rpolling->question;
 ?>
</div>
<!-- content -->
<script type="text/javascript">
 $(function () {
        $('#grafikpolling').highcharts({
            title: {
                text: '<?=$pertanyaan?>',
                x: -20 //center
            },
            subtitle: {
                  text: 'Grafik Hasil Polling',
                x: -20
            },
            tooltip: {
					formatter: function() {
						return '<b>'+
				this.point.name +'</b>: '+ Highcharts.numberFormat(this.percentage, 2) +' % ('+ this.y +' Vote)';
					}
				},
				plotOptions: {
					pie: {
						allowPointSelect: true,
						cursor: 'pointer',
						dataLabels: {
							enabled: true,
							color: '#000000',
							connectorColor: '#000000',
							formatter: function() {
								return '<b>'+ this.point.name +'</b>: '+ Highcharts.numberFormat(this.percentage, 2) +' %';
							}
						}
					}
				},
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'middle',
                borderWidth: 0
            },
            series: [{
              type: 'pie',
                name: 'Respon',
                data: [
					<?php
						//$query=$this->db->query("SELECT * FROM t_polling")->row();

                        $data = $this->db->query("SELECT answer1, answer2,answer3,answer4, vote1, vote2,vote3, vote4 FROM t_polling where id='1'")->row();
							// $jumlah = $data->jumlah;
							?>
                            ['<?php echo $data->answer1?>',   <?php echo $data->vote1;?> ],
                            ['<?php echo $data->answer2?>',   <?php echo $data->vote2;?> , ],
                            ['<?php echo $data->answer3?>',   <?php echo $data->vote3;?> , ],
                            ['<?php echo $data->answer4?>',   <?php echo $data->vote4;?> , ],
                         <? //}?>
                    ]
            }]
        });
    });
</script>

<script src="<?php echo base_url(); ?>assets/highcharts/js/highcharts.js"></script>
<script src="<?php echo base_url(); ?>assets/highcharts/js/modules/exporting.js"></script>
<div id="grafikpolling"></div>
  </div>
</div>
</div>
<? $this->load->view('ifooter');?>

Output (Hasil)

Tampilan form vote polling

Tampilan grafik hasil vote

Update 8 Agustus 2015

Bagi anda yang ingin code ini saya share tinggal koneksikan databasenya saja.

Download Code

Postingan Terkait
» Mengganti Dukungan Bahasa Pada Codeigniter 3.xx ( 13 Agu 2017 | 17:08:24 , 287 hits )
» Cetak Laporan Format Excel di Codeigniter ( 25 Jan 2017 | 06:39:12 , 1456 hits )
» Membuat Laporan PDF dengan DomPDF di CodeIgniter ( 04 Nov 2016 | 07:42:55 , 4202 hits )
» Edit dan Hapus Foto Upload Codeigniter ( 31 Okt 2016 | 08:25:06 , 6513 hits )
» Membuat Paging dan Search Bootstrap CodeIgniter ( 11 Okt 2016 | 16:26:41 , 10189 hits )