Skip to content

Instantly share code, notes, and snippets.

@xnau
Last active July 10, 2018 19:41
Show Gist options
  • Save xnau/85de9b7e5aba7a0c16840a718c955577 to your computer and use it in GitHub Desktop.
Save xnau/85de9b7e5aba7a0c16840a718c955577 to your computer and use it in GitHub Desktop.
Demonstrates a way to check multiple fields for a match in Participants Database
<?php
/**
* Plugin Name: PDB Multiple Field Match Check
* Description: checks a new Participants Database submission against
* the database for a matching record using multiple fields
* Version: 1.2
*/
add_filter( 'pdb-incoming_record_match', 'xnau_check_for_match', 10, 2 );
/**
* checks the incoming submission for a match in the database
*
* @global wpdb $wpdb
* @param bool $match the current match state
* @param array $post the new submission data
* @return bool true if there is a match
*/
function xnau_check_for_match( $match, $post )
{
// edit this array to set up your match fields
$check_fields = array( 'first_name', 'last_name' );
$where = array();
$values = array();
// set up the check for the same record when updating
$exception = '';
if (isset( $post['id'] ) ) {
$exception = ' `id` <> %s AND ';
$values[] = $post['id'];
}
foreach ($check_fields as $field) {
if ( isset( $post[$field] ) ) {
$where[] = '`' . $field . '` LIKE "%s"';
$values[] = trim( $post[$field] );
}
}
if ( count( $where ) === 0 ) {
//nothing to check
return false;
}
$sql = 'SELECT COUNT(*) FROM ' . Participants_Db::$participants_table . ' WHERE ' . $exception . implode( ' AND ', $where );
global $wpdb;
$result = $wpdb->get_var( $wpdb->prepare( $sql, $values ) );
return $result > 0;
}
@xnau
Copy link
Author

xnau commented Jan 22, 2018

If you're having trouble getting this to match your records, it's really helpful to know the exact contents of the database record you are trying to match. Open your database in phpMyAdmin (or something similar), find the plugin's main table (usually, it's wp_participants_database) and check the record your trying to match to see what the data looks like.

To see what query the function is using, you can have it dumped to your php error log with a line like this, placed just before the last return line of the function:

error_log( __FUNCTION__ . ' query: ' . $wpdb->last_query );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment