Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

php - How to select a <select> statement from database?

I wasnt quite sure how to word the question correctly - but this is merely just out of interest really. Constantly I am having to load information from a database and pre-populate a form with the values. So in the case of the textbox, its easy, i simply set the value:

<input type="text" value="<?=$foo;?>" name="foobar">

However when I come to select boxes I find my code gets quite sloppy, as I need to place a selected value in the line somewhere. So really I have two options, both of which I dislike:

$one = $two = "";
switch ($myval) {
  case "1": $one = " selected";
  case "2": $two = " selected";

}

and then in the HTML:

<select name="myval">
<option value="1"<?=$one;?>>One</option>
<option value="1"<?=$two;?>>Two</option>
</select>

Or the other option is to place a shorthand if statement in the middle of the select:

<select name="myval">
<option value="1"<?=($myval=="1") ? " selected" : "";?>>One</option>
<option value="1"<?=($myval=="2") ? " selected" : "";?>>Two</option>
</select>

Which looks slightly cleaner, however it still bugs me.

Anyone got any much more efficent ways of doing this? its even more annyoing when It is just a Yes/No drop downbox and I have to write stupid if statements for each value.

The same question applies to checkboxes as well.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create an array with the data you want in the output. Loop over it. Generate an option element for each item in it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...