Hi I am trying to display a common message for the results of a php foreach loop. The message has to be displayed before the results, and should not be displayed if there are no results.
<!-- An array coming from the previous page -->
$string = explode(PHP_EOL, trim($_SESSION['grid']));
<!-- HIDE THIS MESSAGE IF THERE ARE NO RESULTS -->
<label>These barcodes don't exist:</label>
foreach ($string as $value) {
<!-- SQL QUERY -->
$query1 = "select addl_item_code_barcode from items where
addl_item_code_barcode = '$value';";
$result = pg_query($db, $query1);
<!-- IF THE VALUES IN THE ARRAY DON'T EXIST IN THE DATABASE THEN IT IS TO
BE DISPLAYED -->
if (pg_num_rows($result) == 0) {
echo $value; echo' ';
}
}
The problem is that multiple values won't be displayed outside the loop, and the results won't be displayed before the loop. How do I solve this?
Don't echo your output immediately, but store it in a string variable and then output it after your label
<?php
// An array coming from the previous page
$string = explode(PHP_EOL, trim($_SESSION['grid']));
$values = "";
foreach ($string as $value) {
<!-- SQL QUERY -->
$query1 = "
SELECT addl_item_code_barcode
FROM items
WHERE addl_item_code_barcode = '$value'
;
";
$result = pg_query($db, $query1);
// IF THE VALUES IN THE ARRAY DON'T EXIST IN THE DATABASE THEN IT IS TO BE DISPLAYED
if (pg_num_rows($result) == 0) {
$values .= "{$value} ";
}
}
if (strlen($values) === 0) {
// HIDE THIS MESSAGE IF THERE ARE NO RESULTS
?><label>These barcodes don't exist:</label><?php
}
$nonexistent = array();
foreach ($string as $value) {
$query1 = "select addl_item_code_barcode from items where
addl_item_code_barcode = '$value';";
$result = pg_query($db, $query1);
if (pg_num_rows($result) == 0) {
array_push($nonexistent,$value);
}
}
if(count($nonexistent)>0){
echo "<label>These barcodes don't exist:</label> <br/>";
foreach($nonexistent as $element){
echo $element . "<br/>";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.