I have a function that checks an entered value against a simple array of values to determine a match (or not).
function validate_unit_type( $result, $value ) {
$pattern = ["U" ,"SE" ,"SHOP" ,"OFF" ,"APT" ,"CTGE" ,"DUP" ,"FY" ,"F" ,"HSE" ,"KSK" ,"MSNT" ,"MB" ,"PTHS" ,"RM" ,"SHED" ,"SITE" ,"SL" ,"STU" ,"TNHS" ,"VLLA" ,"WARD"];
if ( !empty( $value ) && !in_array( $value, $pattern ) ) {
$result['is_valid'] = false;
$result['message'] = 'Invalid Unit Type.';
}
return $result;
}
This works just fine.
The array values in $pattern are held in a MySQL DB table column too, and I’m trying to get the wpdb class to read these values into an array to suit the function.
global $wpdb;
$results = $wpdb->get_results("SELECT unit_type from wpqi_enum_unit_type", ARRAY_A);
Other than adding the above (wpdb) what else do I need to add to the function so it will work?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I’m trying to get the
wpdbclass 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" );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0