Kev
Kev

Reputation: 133

Save and update dropdown "selected" option

I'm trying to create a form that includes a dropdown. On submit, I'm attempting to save the "selected" option so that on future page loads, this value is "selected" as default.

Something along the lines of:

<select name="people">
  <option value="person-1" <?php if($selected=="person-1") echo 'selected="selected"'; ?> >Person 1</option>
  <option value="person-2" <?php if($selected=="person-2") echo 'selected="selected"'; ?> >Person 2</option>
  <option value="person-3" <?php if($selected=="person-3") echo 'selected="selected"'; ?> >Person 3</option>
</select>

I assume the best way to achieve this would be with a MySQL database to save the selected option. I'm just unsure of how to go about this.

Any help would be appreciated.

Cheers

Upvotes: 0

Views: 1265

Answers (1)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

"I assume the best way to achieve this would be with a MySQL database to save the selected option."

The answer to this is "yes".

What you need to do first, is to save the respective data in a database for the given row(s).

An example of this would be, and applying the same for the other values:

INSERT INTO TABLE (col) VALUES ('person-1')

Then retrieve it in a SELECT such as, and for example:

SELECT col, col_2, col_3 FROM TABLE

depending on how many columns you need to use/query with.

I.e. of a ternary operator and fetching over successful results with a while loop.

echo '

<select name="people">
  <option value="person-1" '.($row["col"] == "person-1" ? "selected" : "") .'>Person 1</option>
  <option value="person-2" '.($row["col"] == "person-2" ? "selected" : "") .'>Person 2</option>
  <option value="person-3" '.($row["col"] == "person-3" ? "selected" : "") .'>Person 3</option>
</select>

';

Or, you can use what you presently are using in the <options>. You would need to use the $selected variable inside the loop, yet I find that the ternary operator is easier to use for cases like this.

Example of a while loop, and I used the MySQLi_ API here:

while ($row = mysqli_fetch_array($query))

The dropdown's name attribute could be used in a form using either a POST or GET method, the choice is yours.

You will need to choose the MySQL API of your liking, but keep in mind that the MySQL_* functions/API is deprecated and deleted as of PHP 7.0


Footnotes:

I believe I have given you enough to get you started. I don't usually give answers for questions like these since they are rather broad, yet I found that if I could be of help, then great.

  • It was also too long to be posted as a comment.

You should also read up on using prepared statements since you seem to be new in working with databases.

References:

Other references:

Upvotes: 1

Related Questions