Rajib.Hassan
Rajib.Hassan

Reputation: 93

How to echo a variable which is sent by php form

I have php form which get variable from other page. the code is given below:

<?php
    $fname = "$_POST[fname]";
    $lname = "$_POST[lname]";
//these value getting from another form
?>
<form action="test.php" method="post" class="form-inline vh_pre_reg_form">
<!-- Now I want to send them by this form-->
            <div class="form-group">
                <label>First Name</label>
                <span><?php echo $fname; ?></span>
            </div>
            <div class="form-group">
                <label>Last Name</label>
                <span><?php echo $lname; ?></span>
            </div>
<input name="submit" id="btnValidate" type="submit" value="Submit"/>
</form>

I want, when I will press submit button, these will go on action page test.php and on test.php page, my value will echo or insert it on mysql database but I can not echo or insert to mysql query them on test.php my test.php page code is given below:

<?php
if(count($_POST)>0) {

    /* Validation to check if Terms and Conditions are accepted */
    if(!isset($_POST["submit"])) {
    $message = "<h1>404 error !</h1><br /> <h2>Page not found !</h2>";
    }

    if(!isset($message)) {
        echo "I got submit butt press";
        echo "<br />";
        echo "here is the value : ".$_POST['$fname'];
    }
}
?>

Please solve my problem, if possible, give me full code..

Upvotes: 0

Views: 1612

Answers (2)

Shailesh Katarmal
Shailesh Katarmal

Reputation: 2785

store it into hidden element before submit button in your form like this:

<input type="hidden" name="fname" value="<?php echo $fname; ?>" />
<input type="hidden" name="lname" value="<?php echo $lname; ?>" />
<input name="submit" id="btnValidate" type="submit" value="Submit"/>

And in your test.php file echoing it.

echo $_POST['fname'];   // name of the hidden input element
echo $_POST['lname'];   // name of the hidden input element

Upvotes: 1

Ohgodwhy
Ohgodwhy

Reputation: 50767

You should not be encapsulating your variables in strings, use an array accessor on the super global $_POST. You should also use ternary assignment to check if the variable is set, so that your next question isn't about undefined index errors.

$fname = isset($_POST["fname"]) ? $_POST["fname"] : false;
$lname = isset($_POST["lname"]) ? $_POST["lname"] : false;

Next, don't check if the count of post is greater than zero, instead check that your form variables are posted.

if(isset($fname, $lname)){
    echo $fname . ' - ' . $lname;
}

Note that you also had $_POST['$fname'] which is also not the correct way to access it.

Upvotes: 1

Related Questions