Skip to main content
edited title
Link
Your Common Sense
  • 9.1k
  • 1
  • 22
  • 51

Prepare string for IN clause Use a comma-separated field in MySQLanother SQL query

edited tags
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481
added 316 characters in body
Source Link
joanb
  • 139
  • 4

I was just wondering if there was a better way to write this block of code in php. I have a string with values separated by commas. I need to prepare that string to pass it on to the query using IN clause.

 $sql = "SELECT domain, items FROM rep_skills WHERE report_id = $id ";
 $data = $conn->query($sql)->fetch_object();

 while($data){
     // can this be done in one line? 
     $array =  explode(",",$records['items']$data->items); // string here is 39,40,41
     $items = implode("','",$array);  // string here is '39'39','40','41''41
     // end of block
            
 $query    $result = $conn->query("SELECT description 
           FROM ".$tables[$data->domain]." 
           WHERE item_id IN ('".$items."')";");

     $description = '';
     while($row = $result->fetch_object()){
        $details .= '- '.$row->description;
    }
}

I was just wondering if there was a better way to write this block of code in php. I have a string with values separated by commas. I need to prepare that string to pass it on to the query using IN clause.

 // can this be done in one line? 
 $array =  explode(",",$records['items']); // string here is 39,40,41
 $items = implode("','",$array);  // string here is '39','40','41'
 // end of block
            
 $query = "SELECT description 
           FROM ".$tables[$data->domain]." 
           WHERE item_id IN ('".$items."')";

I was just wondering if there was a better way to write this block of code in php. I have a string with values separated by commas. I need to prepare that string to pass it on to the query using IN clause.

 $sql = "SELECT domain, items FROM rep_skills WHERE report_id = $id ";
 $data = $conn->query($sql)->fetch_object();

 while($data){
     // can this be done in one line? 
     $array =  explode(",",$data->items); // string here is 39,40,41
     $items = implode("','",$array);  // string here is 39','40','41
     // end of block
            
     $result = $conn->query("SELECT description 
           FROM ".$tables[$data->domain]." 
           WHERE item_id IN ('".$items."')");

     $description = '';
     while($row = $result->fetch_object()){
        $details .= '- '.$row->description;
    }
}
deleted 31 characters in body; edited tags; edited title
Source Link
200_success
  • 145.7k
  • 22
  • 191
  • 481
Loading
Source Link
joanb
  • 139
  • 4
Loading