Constructing <select><option> list with SELECT results

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Constructing <select><option> list with SELECT results

Post by Pavilion »

Hello:

I hope this is the correct forum for this question.

I am trying to construct a dynamic <select><option> list based off of results from a SELECT statement. And I'm running into problems. Specifically - the final output looks like the attached .png file.

There is an extra \ slash in the last </option> tag. Even though I don't have the \ slash in the code snippet. Following is my code snippet. Does anyone have any idea why the forward slash is being inserted into my </option> tag????

Code: Select all

$prep_LogAccess = $link->prepare($select_LogAccess);
		$prep_LogAccess->execute(array());
	
		$list = "<option value=''>test</option>";
	
	$LogAccess_Results = $prep_LogAccess->fetchAll();
	foreach($LogAccess_Results as $LogAccess) {
	$list = $list .  "<option class='optPrivileges' value=" . $LogAccess['ActivityCode'] . ">" . stripslashes($LogAccess['ActivityDesc'])  . "</option>";
	}
		
	echo(json_encode($list));
Thanks in advance - Pavilion
Attachments
selectOption.png
selectOption.png (45.44 KiB) Viewed 63501 times
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Constructing <select><option> list with SELECT results

Post by Pavilion »

Figured it out. I don't need to json_encode() the $list variable. Once I simply echoed it, all was well...
thinsoldier
Forum Contributor
Posts: 367
Joined: Fri Jul 20, 2007 11:29 am
Contact:

Re: Constructing <select><option> list with SELECT results

Post by thinsoldier »

off-topic advice: avoid bouncing back and forth between html and php as much as possible it will save you from countless small bugs. Consider using and array to contain list items. You may find it useful to have them in an array for various reasons in the future.

Code: Select all

$list = $list .  "<option class='optPrivileges' value=" . $LogAccess['ActivityCode'] . ">" . stripslashes($LogAccess['ActivityDesc'])  . "</option>";

Code: Select all

$list = [];
$option_template = '<option class="optPrivileges" value="%s"> %s </option>';
foreach( $foo as $bar ) {
    $list[] = sprintf( $option_template , $LogAccess['ActivityCode'] , stripslashes($LogAccess['ActivityDesc']) );
}

echo implode('',$list);
Warning: I have no idea what I'm talking about.
Post Reply