Drop down menu with integer values does not stay selected after refreshing the page

I have a drop down menu and the user can select a number from one to four. Here is the code:

<!DOCTYPE html> <html> <body> <?php if (isset($_POST['Submit1'])) { $SiteNumber = $_POST['SN']; $fileName = 'test.txt'; $lines = file($fileName); $lines[0]="Site_number= ". $SiteNumber; file_put_contents($fileName, implode($lines)); } else { $fileName = 'test.txt'; $lines = file($fileName); $SiteNumber=explode(" ",$lines[0]); $SiteNumber=$SiteNumber[1]; } ?> <form action="test.php" name ="form1" Method ="POST"> Site Number: <select selected="selected" name="SN" VALUE="<?PHP print $SiteNumber ; ?>"> <?php $attr= 'selected="selected"'; ?> <option VALUE="1" <?php echo $SiteNumber == '1' ? $attr : ''; ?>>1</option> <option VALUE="2" <?php echo $SiteNumber== '2' ? $attr : ''; ?>>2</option> <option VALUE="3" <?php echo $SiteNumber == '3' ? $attr : ''; ?>>3</option> <option VALUE="4" <?php echo $SiteNumber== '4' ? $attr : ''; ?>>4</option> </select> <Input Type = "Submit" Name ="Submit1" Value = "Save Parameters"> </form> </body> </html>

The problem is that the selected number goes back to 1 when I refresh the page although it is supposed to show the selected value and read it from the text file. The error I am getting in the log is : Undefined variable: SiteNumber

so I have tried (in) $_POST['SN'] but no luck. Any help would be appreciated.

-------------Problems Reply------------

Have a look at this line $lines[0]="Site_number= ". $SiteNumber;

I think this is a resource and not an array. You may have to set this as an array before you can assign a value to it. try adding this line instead

$line[0]="Site_number= ". $SiteNumber;

Oh, I tried running your code basically how you have it, and got it to work - I saw the value coming from $SiteNumber = $_POST['SN'];

here this worked for me:

if (isset($_POST['Submit1'])) {
$SiteNumber = $_POST['SN'];
$fileName = 'test.txt';
$lines = fopen($fileName, "w");
$line[0]="site number= ".$SiteNumber;

fwrite($lines, implode($line));

} else {

$fileName = 'test.txt';

$lines = fopen($fileName, "r");
$SiteNumber = fgets($lines);

$SiteNumber=explode(" ",$SiteNumber);
$SiteNumber = $SiteNumber[2];


You have to change dropdown to like this

Site Number:
<select name="SN">
<?php $attr= 'selected="selected"'; ?>

<option VALUE="1" <?php echo $SiteNumber == '1' ? $attr : ''; ?>>1</option>
<option VALUE="2" <?php echo $SiteNumber== '2' ? $attr : ''; ?>>2</option>
<option VALUE="3" <?php echo $SiteNumber == '3' ? $attr : ''; ?>>3</option>
<option VALUE="4" <?php echo $SiteNumber== '4' ? $attr : ''; ?>>4</option>


Category:php Views:3 Time:2018-10-30
Tags: php html

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.100 (s). 11 q(s)