Home > database >  when clicking a button in a php page pass variables to another php page
when clicking a button in a php page pass variables to another php page

Time:08-12

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?

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  style="margin:auto; width:50%; margin-top:100px; min-height:200px">
  <div >
  <?php foreach ($data["items"] as $item){
      echo "<strong>". "food name:  </strong>". $item['name'] . "<br>";
      $name=$item['name'];} ?>
  </div>
  <div >
    <p > <?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 >
  
  </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 ?>

CodePudding user response:

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']

  • Related