我想创建一个投票系统来选择一个新的村庄。我如何才能为候选人投票?
每位用户只能投票一次。
我的代码(我知道这是错的):
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');
}
答案 0 :(得分:0)
首先,我猜你已经记录了用户或提交的用户,而不是尚未登录的访客/匿名用户或未提交他姓名的输入。否则代码工作流程会有所不同。
数据库中的表:
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]
代码将是:
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 you can try update: $this->db->update('vote_table', $data, $where);
}
else
{
//insert data
$this->db->insert('vote_table', $data);
}
redirect('voter/voter_sukses');
}