Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

when clicking a button in a php page pass variables to another php page

I have a PHP page where users can search for food using an API and then display the food information and calories and then click a button to add the food information to their day which is another PHP file however I tried to store the food name and calories in variables and pass them to the other PHP file when clicking on the button using GET but I get this error

: Undefined array key "name"

my question is: how to pass the food data to another PHP file when clicking on a button?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

here is the code that iterates over the food data and prints them and then I stored calories and food name in variables ($name and $cal) and tried to pass the name when clicking the button

 `<?php if (isset($data)){?> //$data is the API response
  <div class="card text-center" style="margin:auto; width:50%; margin-top:100px; min-height:200px">
  <div class="card-header">
  <?php foreach ($data["items"] as $item){
      echo "<strong>". "food name:  </strong>". $item['name'] . "<br>";
      $name=$item['name'];} ?>
  </div>
  <div class="card-body">
    <p class="card-text"> <?php
  foreach ($data["items"] as $item)
  {
      
      echo "Serving size: " . $item["serving_size_g"] . " gram  <br>";
      echo "Calories: ". $item["calories"] . "<br>";
      $cal=$item["calories"];
      echo "Protein: ". $item["protein_g"] . " gram  <br>";
      echo "Carbohydrates: ". $item["carbohydrates_total_g"] . " gram  <br>";
      echo "Fat: ". $item["fat_total_g"] . " gram  <br>";

  }
    $name=$data['items'][0]['name'];   ?></p>
    
    <button><a href="addfood.php?$name">Add Food</a></button>

  </div>
  <div class="card-footer text-muted">
  
  </div>
<?php } ?>
</div>
 
</body>
</html>`

trying to print the variable in the other PHP file which is named addfood.php :

<?php $x=$_GET['name']; echo $x ?>

>Solution :

You’re setting the GET superglobal slightly wrong. The link needs to look something like this:

<button><a href="addfood.php?name=<?=$name?>">Add Food</a></button>

Basically, you need to make a GET with the name ‘name’, and give it the value of your $name variable. If you do it like this, the next page will have the value of $name in $_GET['name']

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading