简体   繁体   中英

How to pass a value from a page to another page in PHP

Im trying to pass a variable value from a page to another page. Im using to go to the next page and I use Session to get the value,

the link variable does working but the price variable doesn't work

Here's the code: index.php

<?php 

  require('connect.php');
  if(!isset($_SESSION)){
    session_start();
  }

 $query  = mysqli_query($connection, "SELECT link, price FROM funnyture WHERE category ='Bed' or category = 'Chairs' or category = 'Tables'") or die("Couldn't find search");
    $count = mysqli_num_rows($query);

    if($count == 0) {
      $output = "There was no row in array";

    } else {

      while($row = mysqli_fetch_array($query)) {
        $link = $row['link'];
        $price = $row['price'];

        echo '

        <form action="Orderform.php" method="post" class="formClass">

          <input name="link" type="image" src="'.$link.'" value="'.$link.'" class="inputClass">
        </form>';
      }
    }   
?>

Orderform.php

<?php include 'navbar2.php' ;?>

    <div class="left">
      <?php
      $_SESSION['link'] = $_POST['link'];
       // $_SESSION['price'] = $_POST['price'];
       echo '<img src="'.$_SESSION['link'] .'">';  
       echo '<p>'.$_GET['price'].'</p>';

      ?>

Help me :)

Only values that are sent by a form will be in the GET or POST array.

From what you are showing I conclude that you don't want to show the field in your form, so make it hidden.

Add this inside your form tag:

<input name="price" type="hidden" value="'.$price.'" class="inputClass">

Also, if you are going to use these values to access the database, be more careful with just taking in variables like this, assume that all user input is wrong and/or dangerous. You would want to look at things like SQL injection and mysqli_escape_string

You are fetching the price using get method and you have not passed it in your redirect url . If you want to fetch that variable on other page using get method then pass it in action url as :

<form action="Orderform.php?price=<?php echo $price; ?>" method="post" class="formClass">

and fetch as :

$price =  $_GET['price'];

Or otherwise pass it using a hidden field inside form and fetch using post method.

<input name="price" type="hidden"  value="'.$price.'" class="inputClass">

and fetch like:

$price = $_POST['price'];

Data can be Send in multiple ways

  1. GET or POST
  2. Using Session
  3. Using cookie

in your orderform.php you are forgot to start session.

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