mdmartiny Posted August 26, 2016 Share Posted August 26, 2016 echo '<option value="'.$user_data['id'].'"'.if ($user_data['id'] == $opened['id']){"selected"}.'>'.$user_data['fullname'].'</option>'; Can someone please explain why this is not working properly? What am I doing wrong Quote Link to comment https://forums.phpfreaks.com/topic/302016-why-is-this-code-breaking-my-page/ Share on other sites More sharing options...
ginerjm Posted August 26, 2016 Share Posted August 26, 2016 Try this instead since you can't insert the normal IF statement in an echo: if ($user_data['id'] == $opened['id']) $sel = 'selected'; else $sel = ''; echo "<option value='{$user_data["id"]}' $sel>{$user_data["fullname"]}</option>"; You could also use the ternary if operator but I never do. Note use of " and {} to condense the statement. (Hope I didn't make a typo here. Couldn't paste my code into this post for some reason.) Quote Link to comment https://forums.phpfreaks.com/topic/302016-why-is-this-code-breaking-my-page/#findComment-1536694 Share on other sites More sharing options...
ginerjm Posted August 26, 2016 Share Posted August 26, 2016 Forgot to mention. If you turned on php error checking you would probably have received a hint as to what the problem was. See my signature.4 Quote Link to comment https://forums.phpfreaks.com/topic/302016-why-is-this-code-breaking-my-page/#findComment-1536699 Share on other sites More sharing options...
Jacques1 Posted August 26, 2016 Share Posted August 26, 2016 And you need to HTML-escape your variables. You can't just drop random strings into your markup and assume that they won't interfere with the rest of the page. In the worst case, this can be used to inject malicious code (also known as cross-site scripting). <?php function html_escape($raw_input, $encoding) { return htmlspecialchars($raw_input, ENT_QUOTES | ENT_SUBSTITUTE, $encoding); } <?php const APP_HTML_ENCODING = 'UTF-8'; // insert your encoding here echo '<option value="'.html_escape($user_data['id'], APP_HTML_ENCODING).'" '.($user_data['id'] == $opened['id'] ? 'selected' : '').'>'.html_escape($user_data['fullname'], APP_HTML_ENCODING).'</option>'; Of course the best solution is to avoid this kind of PHPHTML spaghetti code altogether. Quote Link to comment https://forums.phpfreaks.com/topic/302016-why-is-this-code-breaking-my-page/#findComment-1536701 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.