Bagus Bala Bagus Bala - 1 month ago 17
PHP Question

Vote System Candidate

i want to create a vote system to choose a new head village. Can you help me make a function to vote the candidate ?

each user can vote only once.

My code. ( i know this will be wrong )

function vote_calon(){

$id_calon = $this->input->post('id_calon');
$voted= $this->input->post('voted');
$data = array(
'voted' => 'set ++1',
);

$where = array(
'id_calon' => $id_calon,

);

$this->Admin_dcalon->vote_calon($where,$data,'calon');

redirect('voter/voter_sukses');
}

Answer

i think you are new in CI or even in PHP. but its fine. thats why we need stackoverflow

First, i guess you have already logged user or submitted user, not guest/anonymous which not login yet or not submit input of his name. otherwise the code workflow will be different.

Table in your db

table
#calon_table => profile of governor or person who will voted 
id [int auto_increment]
name [varchar]

#user_table = profile of user who will vote
id [int auto_increment]
name [varchar]
password, avatar, and another information here

#vote_table = table to store vote result
id_user [int ,PRIMARY KEY, foreign key of user_table.id] //while this set as Primary Key , you are never get duplicate user for voting
id_calon [int ,foreign key of calon_table.id]

AND the code will be:

function vote_calon(){
    $id_calon = $this->input->post('id_calon'); //example : 2
    $id_user = $this->input->post('voted'); //example: 324234
    $data = array(
        'id_user' =>  $id_user,
        'id_calon' =>  $id_calon
    );

    $where = array(
        'id_user' => $id_user //this is where clause to keep 1 user only can vote 1 governor
    );

    $check = $this->db->where('vote_table', $where);
    if($check->num_rows() > 0)
    {
        echo "you already use your vote"; //this is for make sure user cant vote more than 1
        //OR u can try update: $this->db->update('vote_table', $data, $where);
    }
    else
    {
        //insert data
        $this->db->insert('vote_table', $data);
    }

    redirect('voter/voter_sukses');
}

because you are from indonesia, maybe you can ask me via WA kosong lapan satu dua smbilan kosong kosong enam lapan lapan sembilan kosong