phpmysqlcodeignitersql-insertmysql-error-1062

How to Redirect user to some other page if Duplicate Entry Error Occurs?


I am trying to redirect user to some other page when duplicate Entry Error Occurs. I am using Codeigniter

. I have written the following code, but it displays the error message Duplicate entry '1' for key 'semester_id'.

Kindly check the code and guide me.

Thanks

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');
            }
    }   

EDIT

    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');    

            }       
}
}

ERROR MESSAGE

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

Solution

  • remove try catch and try this

    $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;
     }
    

    it basically mutes the debug for your insert query.in case of error, no insertion takes place hence it will return false.