I'm retaining values in form elements after a form submit. I've got it to work fine with a select box using the following:
<select name="BranchManager" class="formfield" id="BranchManager"onchange="document.forms[0].submit();SEinit();"><option value="">-- Select Manager --</option>
<?php
$area = $_POST['Area'];
if ($area); {
$BMquery = "SELECT DISTINCT Branch_Manager FROM Sales_Execs WHERE AREA = '$area' ".
"ORDER BY Branch_Manager";
$BMresult = mysql_query($BMquery);
while($row = mysql_fetch_array($BMresult))
{
echo "<option value=\"".$row['Branch_Manager']."\">".$row['Branch_Manager']."</option>
";
}
}
$branchmanager = $POST['BranchManager'];
?>
<script type="text/javascript">
document.getElementById('BranchManager').value = <?php echo json_encode(trim($_POST['BranchManager']));?>;
</script>
Which works fine (apologies if it isn't the cleanest/most efficient code, I'm doing my best!) The next field is a text field that needs to be populated based off the Branch Managers name above. So I've used :
<input name="BranchNum" type="text" class="formfield" id="BranchNum" size="3" maxlength="3" />
<?php
$bm = $_POST['BranchManager'];
if ($bm); {
$BNumquery = "SELECT DISTINCT BRANCH_NUM FROM Sales_Execs WHERE Branch_Manager = '$bm' ";
$BNumresult = mysql_query($BNumquery);
}
$branchnum = $POST['BranchNum'];
?>
<script type="text/javascript">
document.getElementById('BranchNum').value = <?php echo json_encode($BNumresult);?>;
</script>
Which isn't working... where am I going wrong here?
You need to put value="<? echo $variableName; ?>" inside the input field
The reason is because a) you're not echo
ing, and b) you must echo
in a different spot than in a select. You must echo in the value
portion of the input.
<?php
$bm = mysql_real_escape_string($_POST['BranchManager']);
if ($bm) {
$BNumquery = "SELECT DISTINCT BRANCH_NUM FROM Sales_Execs WHERE Branch_Manager = '$bm' ";
$BNumresult = mysql_query($BNumquery);
}
$branchnum = $POST['BranchNum'];
?>
<input name="BranchNum"
type="text"
class="formfield"
id="BranchNum"
size="3"
maxlength="3"
value="<?php echo htmlspecialchars($branchnum); ?>" />
As per the comments, they are correct; you should not be using mysql_*
. Instead, look at PDO; though this is outside the scope of your question.
why are you having semicolons after if condition checks?
if ($bm);
if ($area);
This will always terminate the statement and whatever is in the curly braces will always get executed irrespective of the value in $bm or $area
You need mydql_fetch functions to retrive data from $result.
if($row = mysql_fetch_array($BNumresult))
$branchNum = $row[BRANCH_NUM];
why are you using json_encode when your input tag has size = 3?