如何通过仅从表中获取唯一数据来仅在文本字段中显示div的数据?

如何通过仅从表中获取唯一数据来仅在文本字段中显示div的数据?

问题描述:

I'm trying to display some data on a div with 3 fields by getting only the unique values from the table. The query used is working fine in pgAdmin3, but when trying to display it on the page, multiple divs are getting displayed based on an data scanned in the previous page.

Since it is an array, I'm using the foreach to display and that is the reason multiple divs are getting generated, and I don't know how to display data from an array without using loop.

Getting data scanned in the previous page

$strings = explode(PHP_EOL,trim($_SESSION['grid']));

Displaying data in the divs using foreach based on the number barcodes scanned in the previous page

foreach ($strings as $d){ 
$sql = "select distinct size from items where main_group IN(select distinct 
main_group from items where addl_item_code_barcode IN ('$d')) ORDER BY 
size";
$result = pg_query($db, $sql);
$res = pg_fetch_assoc($result);
?> 
<div class="col-sm show-hide">
<input type="text" value="<?php echo $res['size']; ?> " readonly 
style="background-color: #F5F5F5;" class="form-control"><br> 
<input class="form-control" type="text" name="n2" id="n2"/><br>
<select class="form-control">
<option>25%</option>
<option>50%</option>
<option>100%</option>
</select><br>
</div>
<?php }?>

I scanned 2 barcodes in the previous page which has the same value '36' in the field 'size'. Since 2 data was scanned, the loop ran twice and got displayed twice. How do I display it only once.

Here's how the page looks like now. https://ibb.co/qDh425j

Each barcode is linked to an item which has size '36'.

What you need to check is whether there is a data entry error. if each barcode is supposed to uniquely match to certain size, then you need to fix the data in your db.

Otherwise, you need to decide what to do with barcodes which are mapping to an item of the same size.

Lastly you can probably combine the query so you don't need the loop for each barcode something like this

$sa = [];
foreach ($strings as $s) {
    //add single quotes
    array_push($sa, "'".$s."'");
}   
//recreate string with coma
$d=implode(',', $sa);

$sql = "select distinct size from items where main_group IN(select distinct 
main_group from items where addl_item_code_barcode IN ('$d')) ORDER BY 
size";