0

I'm getting duplicate entries with this, how can I fix it please?

<?php

echo "Month". $_POST["Month"];

global $wpdb;
$wpdb->show_errors(); 
$wpdb->print_error(); 

$wpdb->insert( 
    'church', 
    array( 
        'Firstname' => $_POST["Firstname"],
        'Surname' => $_POST["Surname"],
    'Month' => $_POST["Month"],
    'Day' => $_POST["Day"],
    'Email Address' => $_POST["Email"],
    'Mobile Number' => $_POST["Number"]
)
);
?>
3

There is nothing that prevent duplicates here.

When you create the table 'church' is a good idea set a UNIQUE sql index for field email, in this way you can rely on email address to preventing duplicate entries.

As a generic PHP good practice, you should check the existence of a a variable before using it, using isset function:

/* If $_POST['email'] is setted and it is a valid email address */
if ( isset($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {

  global $wpdb;
  $exists = $wpdb->get_var( $wpdb->prepare(
    "SELECT COUNT(*) FROM 'church' WHERE email = %s", $_POST['email']
  ) );

  if ( ! $exists ) {
    /* Your insert code here */
  }

}

P.S. Is also a good idea prepend the WordPress table prefix in front of custom table names.

0
global $wpdb;
$table_user = $wpdb->prefix . 'user';
$email = $_POST['email'];
// first check if data exists with select query
$datum = $wpdb->get_results("SELECT * FROM $table_user WHERE email= '".$email."'");
if($wpdb->num_rows > 0) {
echo "result exists";
}
// if not exist in the database then insert it
else{
$result = $wpdb->insert( 
 $table_token, 
 array( 
    'Firstname' => $_POST["Firstname"],
    'Surname' => $_POST["Surname"],
'Month' => $_POST["Month"],
'Day' => $_POST["Day"],
'Email Address' => $_POST["Email"],
'Mobile Number' => $_POST["Number"]
 )
 );
}
  • Please prefer usage of $wpdb->prepare – bravokeyl Sep 23 '16 at 11:42
  • It would be gret if you could explain the code in addition to posting it. – bravokeyl Sep 23 '16 at 11:43
  • why i use $wpdb->prepare?above code works for me.Please describe me about prepare – HeroWeb512 Sep 23 '16 at 11:56
  • Even though it works it's not a good practice, check $wpdb->prepare and this – bravokeyl Sep 23 '16 at 12:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.