$wpdb->get_results: How return all data from a single column?

Here’s my query:

global $wpdb; 
$result = $wpdb->get_results( "SELECT NAME_MYCOLUMN FROM NAME_TABLE");
foreach ( $result as $row ) 
{
    $data = "$row-> NAME_MYCOLUMN|";  
}
$val = "'/b($data)b/i'"; 
echo $val;

I get this:

Read More
'/b(word1|)b/i' 

where word1 is the last value.

Instead, I would like to have this:

'/b(word1|word2|word3|word4|.......)b/i'

My goal is to get all the column values not only the last.


Thank you all, but the three solutions proposed do not work well. The result is the same 🙁
In my table there are over one hundred words but I have:

'/b(word1|word2|word3|word4|word5|word6|word7|word8|

Is there a solution ?

EDIT

I have understand where’s the error. I have accidentally added into the database as a word with ID9 < word9 and this (<) has broken the code after the word with ID 8

Related posts

3 comments

  1. You could use $wpdb->get_col to fetch an array of values. Then use implode to join them with a |.

    global $wpdb; 
    $result = $wpdb->get_col( "SELECT NAME_MYCOLUMN FROM NAME_TABLE");
    $data = implode('|', $result);
    $val = "'/b($data)b/i'"; 
    
  2. global $wpdb; 
    $result = $wpdb->get_results( "SELECT NAME_MYCOLUMN FROM NAME_TABLE");
    $val = "'/b("; 
    foreach ( $result as $row ) 
    {
      $val .= "$row-> NAME_MYCOLUMN|";
    }
    $val .= ")b/i'"; 
    
    echo $val;
    
  3. You could use GROUP_CONCAT to return all the rows in a single row

    $result = $wpdb->get_results( "
         SELECT 
         GROUP_CONCAT(NAME_MYCOLUMN SEPARATOR '|') as NAME_MYCOLUMN 
         FROM NAME_TABLE
    "); 
    

Comments are closed.