Page 1 of 1

Constructing <select><option> list with SELECT results

Posted: Sat Oct 06, 2018 8:50 am
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

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

Posted: Sat Oct 06, 2018 9:39 am
by Pavilion
Figured it out. I don't need to json_encode() the $list variable. Once I simply echoed it, all was well...

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

Posted: Wed Oct 31, 2018 2:45 pm
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);