以下代码按预期工作:
<?php
//filename is noproblem.php
//Assign each letter a ratio
$ratios = array(
'A' => 1,
'B' => 0.5
);
//Assign each letter a quantity retrieved from POST
$quantities = array(
'A' => $_POST['AQuantity'],
'B' => $_POST['BQuantity']
);
//Assign each letter a value
$values = array(
'A' => ($ratios['A']*$quantities['A']),
'B' => ($ratios['B']*$quantities['B'])
);
echo "Quantity A = "; echo($quantities['A']); echo "<br>";
echo "Value A = "; echo($values['A']); echo "<br>";
echo "Quantity B = "; echo($quantities['B']); echo "<br>";
echo "Value B = "; echo($values['B']);
?>
<html>
<form name="Quantities" action="noproblem.php" method="post">
<br>
<input type="submit" value="Insert">
<br>
Quantity for A<input type="text" name="AQuantity" size="4 "value="<?php if($_POST['AQuantity']>0) {echo htmlspecialchars($_POST['AQuantity']);} else {echo 0;} ?>">
<br>
Quantity for B<input type="text" name="BQuantity" size="4" value="<?php if($_POST['BQuantity']>0) {echo htmlspecialchars($_POST['BQuantity']);} else {echo 0;} ?>">
</form>
</html>
但是,问题是我需要 Quantities 和 Values 变量稍后转移到另一个 PHP 文件中,该文件只能包含 PHP 代码(JPGraph)。这可以通过使用 $_SESSION 变量来实现,但随后表单提交突然需要按两次。违规代码:
<?php
//filename is problem.php
session_start();
//Assign each letter a ratio
$ratios = array(
'A' => 1,
'B' => 0.5
);
$_SESSION = array(
//Assign each letter a quantity retrieved from POST
'quantities' => array(
'A' => $_POST['AQuantity'],
'B' => $_POST['BQuantity']
),
//Assign each letter a USD Value from API data and their respective quantities
'values' => array(
'A' => ($ratios['A']*$_SESSION['quantities']['A']),
'B' => ($ratios['B']*$_SESSION['quantities']['B'])
));
echo "Quantity A = "; echo($_SESSION['quantities']['A']); echo "<br>";
echo "Value A = "; echo($_SESSION['values']['A']); echo "<br>";
echo "Quantity B = "; echo($_SESSION['quantities']['B']); echo "<br>";
echo "Value B = "; echo($_SESSION['values']['B']);
?>
<html>
<form name="Quantities" action="problem.php" method="post">
<br>
<input type="submit" value="Insert">
<br>
Quantity for A<input type="text" name="AQuantity" size="4 "value="<?php if($_POST['AQuantity']>0) {echo htmlspecialchars($_POST['AQuantity']);} else {echo 0;} ?>">
<br>
Quantity for B<input type="text" name="BQuantity" size="4" value="<?php if($_POST['BQuantity']>0) {echo htmlspecialchars($_POST['BQuantity']);} else {echo 0;} ?>">
</form>
</html>
我不能理解 SESSION 是如何工作的,所以在这方面的一些启示将不胜感激。首先,我需要知道如何修复代码,以便在使用 SESSION 时只需按一下按钮即可正确计算。我知道一个不太理想的解决方案是将每个需要的变量复制到 $_SESSION 数组中,并在该文件的主体中使用非 SESSION 变量。当然,还有比这更优雅的方式。