|
-
Feb 28th, 2012, 07:46 PM
#1
Thread Starter
Hyperactive Member
html select in php
Hi Guys,
i have a list of records that i'm displaying in a table, in which i have two select boxes. i managed to populate the options and select the appropriate value but i believe it was inefficient. here is how i do it.
in the table loop, i call a function that queries a table and create a string
PHP Code:
// function im calling
while($row = mysql_fetch_array($aJobs))
{
$sOptionSelected='';
if ($row['job_id']==$jobId){$sOptionSelected='SELECTED';}
$sJobOptions= $sJobOptions . '<option value="'.$row['job_id'].'"'.$sOptionSelected.'>'. $row['job_desc'] .'</option>';
}
is there a better approach to do so? ?
thanks
-
Mar 1st, 2012, 07:10 PM
#2
Addicted Member
Re: html select in php
Hi,
this code seems good, (I didn't change the PHP, but validated it as html code).
PHP Code:
while ($row = mysql_fetch_array($aJobs)) { $sOptionSelected = ''; if ($row['job_id'] == $jobId) { $sOptionSelected = 'selected="selected"'; } $sJobOptions = $sJobOptions.'<option value="'.$row['job_id'].'" '.$sOptionSelected.'>'.$row['job_desc'].'</option>'; }
q. from where do you get the value of $jobId?, please write more code
Feras Jobeir
-
Mar 1st, 2012, 07:22 PM
#3
Thread Starter
Hyperactive Member
Re: html select in php
this works for me, but i was wondering if there was another way of doing it in php. i just think its inefficient in terms of performance.
e.g. if i have a table with a 1000 row, for each row i call a function to query the jobs list and build a string of options, and select the appropriate option value
jobId is a variable passed to the called function.
thanks any way
-
Mar 1st, 2012, 07:36 PM
#4
Addicted Member
Re: html select in php
This depends on your data, how they locate in the database, are they related to others (so we can get them using the least number of queries).
To get a fine answer, please provide the SQL structure of your table(s), and describe a little on how do you want them to appear in the page. 
Feras Jobeir
-
Mar 2nd, 2012, 12:36 PM
#5
Re: html select in php
You could use mysql_data_seek() to re-use your result set and avoid repeating your query.
You could create a single string containing all of your HTML output, and do a preg_replace() for whatever's selected...
PHP Code:
<?php $options = '<option value="1">1</option><option value="2">2</option>'; ?> <select> <?php echo preg_replace('/(value="'.$jobId.'")/', "$1 selected", $options); ?> </select>
...is that a good idea?
What I'd probably choose is to fetch my data once, re-use the result set, iterate it each time (for each <select> element), and output my HTML in-place as it goes (don't make a string of it).
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|