Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nextab/94fb5826e69629a52472d59b8504858e to your computer and use it in GitHub Desktop.
Save nextab/94fb5826e69629a52472d59b8504858e to your computer and use it in GitHub Desktop.
#region CCT Super Custom Lookup - Get everything from CCT
/**
*
* @param array $find_columns array of column names to find
* @param string $table_name - slug of the CCT; global WPDB prefix and 'jet_cct_' will be appended; defaults to 'event_registrations'
* @param string $where - where clause to check against
*
* @return array|null returns an associative array of the $find_columns if something was found for the where clause
*
*
*/
function jet_lookup($find_columns, $where, $table_name = 'event_registrations'): ?array {
global $wpdb;
$final_table_name = $wpdb->prefix . 'jet_cct_' . sanitize_text_field($table_name);
$columns = verify_column_names(array_map('sanitize_text_field', $find_columns), $table_name);
$columns_list = implode(', ', $columns);
// You should ensure that the column names are safe since they cannot be parameterized
// echo '<!-- nxt debug --><pre>'; print_r("SELECT $columns_list FROM $final_table_name WHERE $where"); echo '</pre>';
$query = $wpdb->prepare("SELECT $columns_list FROM $final_table_name WHERE $where");
// Execute the query
$results = $wpdb->get_results($query, ARRAY_A);
// Return the result if available
return $results ? $results : null;
}
#endregion CCT Super Custom Lookup - Get everything from CCT
#region verify column names / security function against SQL injection
/**
*
* @param array $input_columns array of column names to check against the CCT / database table
* @param string $table_name slug of the CCT / database table; global WPDB prefix and 'jet_cct_' will be appended; defaults to 'zmmt_events'
*
* This function is used to check an array of column names against the existing columns inside a given table. It returns an array of valid column names. It is used to increase security against SQL injection.
*
*/
function verify_column_names($input_columns, $table_name = 'zmmt_events'): array {
global $wpdb;
$safe_columns = [];
$mapped_table_name = $wpdb->prefix . 'jet_cct_' . sanitize_text_field($table_name);
// Fetch the list of columns from the database
$columns = $wpdb->get_results("SHOW COLUMNS FROM $mapped_table_name");
if ($columns) {
// Create an array of valid column names
$valid_columns = array_column($columns, 'Field');
// Check each input column against the valid columns
foreach ($input_columns as $column) {
if (in_array($column, $valid_columns)) {
$safe_columns[] = $column;
}
}
}
return $safe_columns;
}
#endregion verify column names / security function against SQL injection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment