skip to Main Content

I have an array with following values:

$test = [2,8,10,12]; 

and a table 'orderdetails' in database with order_title and order_id columns.

What I want is to fetch order_title of every order using order_id in a loop.
Can anyone help?

What I know is:

$test = [2,8,10,12];
foreach($test as $order_id){
$order_name = $wpdb->get_results('SELECT order_title FROM orderdetails WHERE order_id ='. $order_id);
$order_names[] = $order_name;
}

but this will make query run multiple times, any better solution?

UPDATE:

When I try to use IN(), values are getting inserted like this:

SELECT order_title FROM orderdetails WHERE order_id IN(2,8,10,12)

but what problem is here, query is only returning the value for first element in array that is 2

the solution needs to get applied is IN('2','8','10','12')
all the values should be in a single quote, but I don’t know how to achieve that.

2

Answers


  1. You can use WHERE IN :

    $ids = implode("','", [2,8,10,12]); 
    $query = "SELECT order_title FROM orderdetails WHERE order_id IN ('$ids')";
    $order_name = $wpdb->get_results($query);
    

    Query :

    SELECT order_title FROM orderdetails WHERE order_id IN ('2','8','10','12')
    
    Login or Signup to reply.
  2. I’d do it like this:

    $test = [2,8,10,12];
    $inclause = '';
    foreach($test as $order_id){
        $inclause .= $order_id . ',';
    }
    $inclause = rtrim($inclause,',');
    $query = 'SELECT order_title FROM orderdetails WHERE order_id IN ('. $inclause . ')';
    $order_name = $wpdb->get_results($query);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search