I am trying to select a value from the last previous entry, and increment that number by one each time. I have it working to where it selects the current entries value (default 1000) and increments 1 and re-inserts the value back (so ends up 1001 each time). I need it to select the last previous entry of that field instead so it will go 1001,1002,1003 etc. Thanks.
add_action('gform_after_submission_4', 'add_submission_id_four', 10, 2);
function add_submission_id_four($entry, $form) {
global $wpdb;
$field_number = 3;
$table = $wpdb->prefix . 'rg_lead_detail';
$form_id = 4; // update to the form ID your unique id field belongs to
$result = $wpdb->get_var("SELECT value FROM $table WHERE form_id = '$form_id'
AND field_number = '$field_number'");
$result++;
$unique = strval($result);
$wpdb->insert("{$wpdb->prefix}rg_lead_detail", array(
'value' => $unique,
'field_number' => $field_number,
'lead_id' => $entry['id'],
'form_id' => $entry['form_id']
));// update the entry
}
You can use the MAX()
function to get the largest value for that form_id
and field_number
, defaulting to 1000 using IFNULL()
(so that 1001 is the first returned). You can do the +1
in SQL as well so that incrementing $result
is not needed.
I find it good form to use $wpdb->prepare()
as well to handle the arguments.
$sql = "SELECT MAX(IFNULL(value,1000))+1 FROM {$wpdb->prefix}rg_lead_detail WHERE form_id = %d AND field_number = %d";
$result = $wpdb->get_var( $wpdb->prepare( $sql, $form_id, $field_number ) );
$unique = strval($result);