简体   繁体   中英

Is there a way to pass variables / $_POST through foreach statements?

Hey, I'm getting my feet wet with PHP, and was wondering if it was possible if I could put $id = $row['id']; through a $_POST statement,then getting each $_POST variable, and then printing them through a foreach .

Thanks in advance!

order.php:

            foreach ($rows as $row) {
            $food = $row["food"];
            $price = $row["price"];
            $picture = $row["picture"];
            $id = $row['id'];
            echo "<tr>
                    <td><img src='$picture' width='120px' /></td>
                    <td>$food</td>
                    <td>$$price</td>
                    <td><input type='number' min='0' max='10' placeholder='#' name='$id' maxlength='1'></td>
                </tr>";
        }

action.php:

            foreach ($rows as $row){
              $food = $row['food'];
              $price = $row['price'];
              $id = $row['id'];

              if(isset($_POST[$id])){
                $qty = $_POST[$id];
                echo 'set';
                echo $qty;
              }else{
                  echo 'unset';
                  $qty = '';

              }
              echo "<tr>
            <td>$food</td>
            <td>$qty</td>
            <td>$price</td>
        </tr>";      
        }

Change your echo to this:

echo "<tr>
       <td><img src='$picture' width='120px' /></td>
       <td>$food</td>
       <td>$$price</td>
       <td><input type='number' min='0' max='10' placeholder='#' name='qty[".$id."]' maxlength='1'></td>
      </tr>";

Then in your action.php:

foreach ($rows as $row){
          $food = $row['food'];
          $price = $row['price'];
          $id = $row['id'];

          if(isset($_POST['qty'][$id])){
            $qty = $_POST['qty'][$id];
            echo 'set';
            echo $qty;
          }else{
              echo 'unset';
              $qty = '';

          }
          echo "<tr>
        <td>$food</td>
        <td>$qty</td>
        <td>$price</td>
    </tr>";      
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM