如果数据库中已存在id和日期,如何防止插入?

时间:2017-09-30 13:56:45

标签: php mysql codeigniter

表名是" evaluation"列player_idplayer_evaleval_date
我评估玩家每天都会说,所以如果我评估特定玩家,数据将保存在数据库中。现在,如果我将在同一天保存同一个播放器,则不会使用player_id和eval_date插入数据。

任何想法怎么做?由于

PS:player_id不是主键,所以我可以在同一个表中将玩家插入不同日期的相同ID。

 public function update() {
 $players = array();

foreach ($this->input->post('checkbox') as $checkbox) {
    list($value, $player_id) = explode('::', $checkbox);
    self::update_player($players, $player_id, 'player_att1', $value);
}
foreach ($this->input->post('checkbox2') as $checkbox) {
    list($value, $player_id) = explode('::', $checkbox);
    self::update_player($players, $player_id, 'player_att2', $value);
}
foreach ($this->input->post('checkbox3') as $checkbox) {
    list($value, $player_id) = explode('::', $checkbox);
    self::update_player($players, $player_id, 'player_att3', $value);
}
foreach ($this->input->post('checkbox4') as $checkbox) {
    list($value, $player_id) = explode('::', $checkbox);
    self::update_player($players, $player_id, 'player_att4', $value);
}
$this->load->model('Evaluation_model');
foreach ($players as $player_id => $data) {
    $this->Evaluation_model->editview($player_id, $data);
}
redirect(base_url('Evaluations/evaluate'));
}

static function update_player(&$players, $id, $property, $value) {
if (!isset($players[$id])) {
    $players[$id] = array(
        'player_id' => $id,
        'player_att1' => 0,
        'player_att2' => 0,
        'player_att3' => 0,
        'player_att4' => 0,
        'player_atotal' => 0
    );
}
$players[$id][$property] = $value;
$players[$id]['player_atotal'] += $value;
}

2 个答案:

答案 0 :(得分:1)

首先,你需要通过简单检查玩家的数量来检查具有指定日期的玩家是否存在

/* This will get you the count of the player for the specific date */
    $playerAlreadyExistsCount = $this->db
    ->where('player_id', $palyerId)
    ->where('eval_date', $evalDate)
    ->count_all('evaluation');

    if($playerAlreadyExistsCount > 0){
       //Player already exists. You can set a flashdata and show the user that the player is already inserted
    }else{
       //Player is not existing so create the new player here.
    }

答案 1 :(得分:0)

使用 SQL UNIQUE约束条件时,可以防止在已经存在具有相同“id”和相同“date”的另一个行时插入行。 https://stackoverflow.com/a/3474309/2768318,改变您的数据库。

如果你想避免通过PHP插入,你应该先读取所有带有该ID的播放器,然后检查是否有另一个具有相同日期的播放器。