Ozzie
Ozzie

Reputation: 11

How to make the PHP HTML from drop down list remember the last selection?

I am trying to make my drop down list to remember the last selection by the end user. I probably have syntax errors but could not find where I am making the mistake(s). Basically I am using PHP for connecting to an mySQL server to populate a drop down HTML based form menu. Then I let the user select and create a web report. Though I want the last selection to be remembered in the form by default. Can you pls help with my not performing syntax below?

    <?php
        $mysqli = NEW MySQLi($host, $user, $pass, $name);
        $resultSet = $mysqli->query ("SELECT DISTINCT account FROM table");
    ?>
    
   <form action="" method="post">
    <select name = "formAccounts">
        <?php
            while ($rows = $resultSet ->fetch_assoc())
            {
            
                echo '<option value="'.$rows['account'].'"';            
                if($rows['account'] == $_POST['formAccounts']) echo ' selected="selected"';      
                echo '>'.$rows['account'].'</option>'; }

            }
                // Close connection
                mysqli_close($mysqli);
                
        ?>
    </select>

        <?php
          if(isset($_POST['submit'])){
            if(!empty($_POST['formAccounts'])) {
              $selectedAccount = $_POST['formAccounts'];

Then the code continues with web reports...

Upvotes: 1

Views: 214

Answers (2)

koushik naikel
koushik naikel

Reputation: 1

wrong lines:

            echo '<option value="'.$rows['account'].'"';            
            if($rows['account'] == $_POST['formAccounts']) echo ' selected="selected"';      
            echo '>'.$rows['account'].'</option>'; }

correct lines:

   echo '<option value="'.$rows['account'].'"';            
   if($rows['account'] == $_POST['formAccounts'])
     echo ' selected="selected"';      
   echo '>'.$rows['account'].'</option>'; 

you had not started "{" after if statement but end this . So, syntax error. you need to remove this closer "}" .

and also should be

$mysqli = new mysqli($host, $user, $pass, $name);

not should be

$mysqli = NEW MySQLi($host, $user, $pass, $name);

Upvotes: 0

Dave
Dave

Reputation: 21

if($rows['account'] == $_POST['formAccounts']) echo ' selected="selected"';

//You are missing one "=" and a space before the first selected i think.

Upvotes: 1

Related Questions