如果发生重复输入错误,如何将用户重定向到其他页面?

时间:2014-07-07 06:24:41

标签: php mysql database codeigniter duplicates

我正在尝试将重复输入错误发生时将用户重定向到其他页面。我在用 Codeigniter

。我编写了以下代码,但它显示错误消息Duplicate entry '1' for key 'semester_id'

请检查代码并指导我。

由于

public function insert_sports_sports($student_id, $squash, $football, $cricket, $hockey, $swimming, $semester_id)
{
    $data= array (

            "squash"=> $squash,
            "football"=>$football,
            "cricket"=>$cricket,
            "hockey"=>$hockey,
            "swimming"=>$swimming,
            "studentId"=>$student_id,
            "semester_id" => $semester_id

    );  

    if ($this->db->insert("sports",$data))
    {
        return true;
        }
        else
        {
            return false;
            }
    }

CONTROLLER

---
--
--
    if($this->loginmodel->insert_sports_sports($student_id, $squash, $football, $cricket,
                                             $hockey, $swimming, $semester_id))
    {
        redirect('mycontroller/index');
        }
        else
        {
            $this->load->view('success');
            }
    }   

修改

    if ($this->db->insert("sports",$data))
    {
        return true;
        }
        else
        {
            return false;
            }
    }


catch (Exception $ex) {

        if($ex->message == "Duplicate entry '1' for key 'semester_id'")
        {
            redirect('success.php');    

            }       
}
}

错误消息

A Database Error Occurred

Error Number: 1062

Duplicate entry '1' for key 'semester_id'

INSERT INTO `sports` (`squash`, `football`, `cricket`, `hockey`, `swimming`, `studentId`, `semester_id`) VALUES ('4', '4', '4', '4', '4', '42', '1')

Filename: F:\xampp\htdocs\student_management2\system\database\DB_driver.php

Line Number: 330

3 个答案:

答案 0 :(得分:3)

如果您只想重定向错误

try {
    $data= array (

            "squash"=> $squash,
            "football"=>$football,
            "cricket"=>$cricket,
            "hockey"=>$hockey,
            "swimming"=>$swimming,
            "studentId"=>$student_id,
            "semester_id" => $semester_id

    );  

    if ($this->db->insert("sports",$data))
    {
        return true;
        }
        else
        {
            return false;
            }
    }
}
catch (Exception $ex) {
    if($ex->message == "Duplicate entry '1' for key 'semester_id'")
        redirect('yourpage.php');
}

答案 1 :(得分:3)

删除try catch并尝试此

$orig_debug = $this->db->db_debug;
$this->db->db_debug = FALSE;

if ($this->db->insert("sports",$data))
 {
    $this->db->db_debug = $orig_debug;
    return true;
 }
else
 {
   $this->db->db_debug = $orig_debug;
    return false;
 }

它基本上会使插入查询的调试静音。如果出现错误,则不会发生插入,因此它将返回false。

答案 2 :(得分:2)

您可以通过设置semester_id的规则来阻止它,如下所示

$this->form_validation->set_rules('semester_id', 'input_name', 'trim|required|is_unique[TABLENAME.COLUMNNAME]');