How to detect a duplicate record when inserting to datatabase

How to detect a duplicate record when inserting to datatabase

antonis80antonis80 Posts: 18Questions: 8Answers: 0

I am using the PHP editor and i need to perform a check whether a new record already exists in my mysql table. The query is based on values of 2 of the input fields i am submitting. How can i do that? What i have found from the forums is the following:

"Editor::inst( $db, 'xm_programmes', 'ID' )
->fields(
Field::inst( 'P' )->validator( function($val, $data, $db) {
if ( empty($val) ) {
return "This field is required.";
}
$checkduplicate = $db
->select( 'xm_programmes', 'ID', array(
'P' => $_POST['data']['P']
) )
->count();
if($checkduplicate !== 0){
return "Duplicate !";
}elseif(!is_numeric($val)){
return "This field must be numeric only.";
}
return true;
} ),"

However this only performs a query based on one of the submitted fields.

Thank you

Answers

  • VarshneyVarshney Posts: 9Questions: 1Answers: 0
    edited November 2016

    What database are you using? If you're using MySQL then use InnoDB as the engine. Once that is set then you can automatically have the database engine run the duplication check itself.

    I assume that the two fields are in the same table? If that's the case then set both columns to unique.

  • allanallan Posts: 63,823Questions: 1Answers: 10,517 Site admin

    Editor's PHP libraries have a built in unique validator which can be used to check for duplicates.

    Allan

This discussion has been closed.