p3ace p3ace - 1 month ago 7
PHP Question

Passing php variable as hidden input where html is contained in one echo

I'm new with PHP and still learning.

<?php
if(isset($_POST['btnLogin'])){
$myVariable = $_POST['fieldParameter'];

if(condition){
//do something
}else{

echo "
<form method='POST' action='submit.php'><br/>
<input type='hidden' name='myVariable' value='<?php echo $myVariable; ?>'/>
<br/>
<input type='submit' name='btnSubmit' id='submit' value='Submit'>
</form>

";
}
}
?>


Notice that the variable
$myVariable
is contained in the main
IF
block. I'm trying to send the value of
$myVariable
to submit.php as hidden field.

Also, i enclosed all the html tags using one
echo
statement with double quotes.

I found related questions here in
SO
but can't find similar to embedding
php
within a long
echo
of
html
tags

I tried to put
value='<?php echo $studentNo; ?>'
with no success.

I want to access it in a submit.php file like this,

submit.php

<?php
$aVariable = $_POST['myVariable'];
echo $aVariable;
?>


How can I pass the value contained in
$myVariable
as hidden field? Is there something wrong with the way I use double and single quotes?

Thank you.

Answer

You just need to type $myVariable instead of in your string. Double quotes "" only creates a string literal. It doesn't directly output data like inline HTML. As you can see from the syntax coloring in StackOverflow, the

You can try these variants (simplified):

// code before
echo "<input type='hidden' name='myVariable' value='$myVariable'/>";
// code after

// OR //

// code before
?>
<input type='hidden' name='myVariable' value='<?= $myVariable ?>'/>
<?php
// code after

Note that the quotes you use in HTML don't affect PHP, as long as you escape them properly (use \" and \' where appropriate).

See HTML output from web server for more information.