Jump to content

Why is this code breaking my page?


mdmartiny

Recommended Posts

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.)

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.