0

I'm having difficulty determing how to perform a select on an array in my WordPress database.

I have the following:

$results = $this->wpdb->get_results("SELECT JobId, title, category, description, cities, states FROM ".$this->tableName." WHERE states = 'SC'");

The states are (unfortunately) in a an array that contains strings, like so:

AL, CA, CA

AL, MN, FL, NM, TX

CO
FL, SC, SC, SC

NM

SC

Some of the JobIDs are in multiple states, or in the same state, but different cities.

I have a filter (HTML form input/drop-downs), where I can select results by keyword, states, or category. I want to select all results from the table that that match the selections in my form. Using my example above, I want to receive all results that contain 'SC'. I should receive 2 results.

Based on other similar answers, such as this (mysql: how to select imploded array value), Here's what I've tried:

public function getJobs()
{
    $result = [];
    $category = $this->wpdb->get_results("(SELECT states FROM ".$this->tableName." WHERE FIND_IN_SET('SC','states')
            UNION 
            (SELECT JobId, title, category, description, cities FROM ".$this->tableName." WHERE ".$query.") 
            ORDER BY category ASC");
    foreach ($category as $row){
        $result[$row->category] = $row->category;
    }

    return $result;
}

I was hoping to search the states array, which contains strings, and combine that with another search on the other columns. I tried explode, but that didn't work, because it's an array.

Originally, I had this:

$postings = $this->wpdb->get_results("SELECT JobId, title, category, description, cities, states FROM ".$this->tableName." WHERE ".$query." ORDER BY created_at ASC");

...which works fine for displaying all results by category. Right now, I'm just trying to generate results by state.

(Note: I've been reading that querying a string isn't the right option, and inserting the data into the database (from my JSON file) is the better way to do this. Unfortunately, I couldn't figure that out over the past couple of days. I'll continue to keep going through other posts though.)

Just some pointers in the right direction would be appreciated.

Thanks.

Stephen

ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
Stephen
  • 183
  • 2
  • 15
  • in mysql there is not array data type .. your data sample seems string comma separated values .. – ScaisEdge Aug 15 '19 at 19:59
  • 1
    Just change your first query to `$results = $this->wpdb->get_results("SELECT JobId, title, category, description, cities, states FROM ".$this->tableName." WHERE FIND_IN_SET('SC', states)");` Note that there are **no** quotes around `states` as it is a column name, not a string. – Nick Aug 15 '19 at 23:25

0 Answers0