I’m trying to get the
wpdb
class to read these values into an array to suit the function
You could manually loop through the $results
array to build the $pattern
array, but a much simpler way is by using $wpdb->get_col()
to get all the values of the unit_type
column:
$pattern = $wpdb->get_col( "SELECT unit_type from wpqi_enum_unit_type" );
/* Alternate version (i.e. manually loop through $results):
$pattern = array();
$results = $wpdb->get_results( "SELECT unit_type from wpqi_enum_unit_type" );
foreach ( $results as $row ) {
$pattern[] = $row->unit_type;
}
*/
Additional Code
This is just a suggestion: Instead of doing in_array()
(in validate_unit_type()
), you could also do like so, which uses $wpdb->get_var()
:
if ( ! empty( $value ) ) {
// This way, there'd be no need for the $pattern.
$count = (int) $wpdb->get_var( $wpdb->prepare( "
SELECT COUNT(*) from wpqi_enum_unit_type
WHERE unit_type = %s
LIMIT 1
", $value ) );
if ( $count < 1 ) {
$result['is_valid'] = false;
$result['message'] = 'Invalid Unit Type.';
}
}
Additional Note
I’m assuming that wpqi_
is the table prefix, so instead of hard-coding it, I suggest you to use $wpdb->prefix
. E.g.
$table = $wpdb->prefix . 'enum_unit_type';
$pattern = $wpdb->get_col( "SELECT unit_type from $table" );