Skip to content
Advertisement

PHP – Pass array values to mysql query and fetch the result

$dataSet = Array ( 
    [0] => Array ( [quantity] => 22 [sr_no] => 71 [batch_id] =>5 [inq_id] => 91 ) 
    [1] => Array ( [quantity] => 35 [sr_no] => 72 [batch_id] => [inq_id] => 92 ) 
    [2] => Array ( [quantity] => 20 [sr_no] => 69 [batch_id] => [inq_id] => 90 ) 
    [3] => Array ( [quantity] => 45 [sr_no] => 75 [batch_id] => 6 [inq_id] => 94 ) 
    [4] => Array ( [quantity] => 15 [sr_no] => 70 [batch_id] => 6 [inq_id] => 90 ) 
)

I’ve the above array from which I need to get each sr_no, batch_id and need to check whether the combination is present (eg. the first row sr_no => 71 & batch_id => 5) in a table ( part_list ). I’ve tried the below code but it is fetching all. Ready to implement if there is any better approach also.

$keyedExistingPartRows = array_column(
    $this->db
        ->where_in('batch_id', array_column($dataSet, 'batch_id'))
        ->where_in('sr_no', array_column($dataSet, 'sr_no'))
        ->get('part_list')
        ->result_array(),
    null,
    'sr_no'
);

Thanks in advance.

Advertisement

Answer

From what I understand you want to check for both sr_no and batch_id. If you are willing to use raw SQL query you can first concat the two columns and then provide the array for that concatinated column and find the desired result.

please try this

$temp_Arr = [];

foreach($dataSet as $val){
    $temp_Arr[] = $val['sr_no']."-".$val['batch_id'];    
}
$sr_no_and_batch_id = "('".implode("', '", $temp_Arr)."')";
//echo $sr_no_and_batch_id;

$sql="SELECT * FROM `part_list` WHERE CONCAT(sr_no, '-', batch_id) IN $sr_no_and_batch_id";    
$query = $this->db->query($SQL);
return $query->result_array();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement