Reputation: 371
I am getting an array in POST having 2 fields and based upon first field fetching the matched data from mysql table to display, it works fine till here. but second fields in array may be empty and I do not want to display them here is my code.
<p class="yorder">
<?php
foreach ($_POST as $key => $value) {
$exp_key = substr($key, 0, 1);
if($exp_key[0] == 'p'){
if($i % 2 != 0){
$tprod = mysql_real_escape_string($value);
$sql = "SELECT * FROM menuitem WHERE prodname = '". $tprod ."'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
?>
<span class="o1"> </span>
<span class="o2"><?php echo $value; ?></span>
<?php } if($i % 2 != 0){ $i++; continue;} ?>
<span class="o3"><?php echo $value; ?></span>
<span class="o4"><?php echo $value * $row['price']; ?></span>
<?php $i++;}
}
?>
</p>
here is the screen shot of my result
thanks
my logic is : first I check 1st array item with database and get its value, then I continue the loop and get the 2nd array item and display it.
What I am trying to do now is: I am getting this array in POST Array ( [prodname0] => Chicken Sandwich [port-0] => [prodname1] => Roasted Chicken Sandwich [port-1] => 2 [prodname2] => Tanu's Special Chicken Sandwich [port-2] => 2 [prodname3] => Cheese Sandwich [port-3] => [prodname4] => Chicken Salami Sandwich [port-4] => [prodname5] => Chicken Ham Sandwich [port-5] => [prodname6] => Egg and Mayoinnaise Sandwich [port-6] => [prodname7] => Bhetki Fry [port-7] => [prodname8] => Pao Bhaji [port-8] => [prodname9] => Puffs [port-9] => [prodname10] => Chicken Cutlet [port-10] => [prodname11] => Mutton Chop [port-11] => [prodname12] => Egg Devil [port-12] => [prodname13] => Paneer Cutlet [port-13] => )
Can I change it to like : Chicken Sandwich => Roasted Chicken Sandwich => 2 this will do my job I think
Upvotes: 0
Views: 127
Reputation: 10121
Replace your php code with this
<?php
foreach ($_POST as $key => $value) {
$exp_key = substr($key, 0, 1);
if(!empty($key) || !empty($value)){ //edited portion
if($exp_key[0] == 'p'){
if($i % 2 != 0){
$tprod = mysql_real_escape_string($value);
$sql = "SELECT * FROM menuitem WHERE prodname = '". $tprod ."'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
?>
<span class="o1"> </span>
<span class="o2"><?php echo $value; ?></span>
<?php } if($i % 2 != 0){ $i++; continue;} ?>
<span class="o3"><?php echo $value; ?></span>
<span class="o4"><?php echo $value * $row['price']; ?></span>
<?php $i++;}
}
} //edited portion
?>
Upvotes: 0
Reputation: 1722
A simple solution would be to do this:
foreach ($_POST as $key => $value) {
if(empty($value){
continue;
}
// Other code
}
First check if the POST value is empty and if it is, use the continue
keyword to skip the rest of the code in the loop.
Upvotes: 1