What is the best way to echo results from the database into html code in PHP?

后端 未结 5 1913
伪装坚强ぢ
伪装坚强ぢ 2021-01-15 05:04

when I have a value like this in the database (\"foo\")

how can I echo it without any conflict with html code

notice



        
相关标签:
5条回答
  • 2021-01-15 05:26

    htmlspecialchars() basically, for example

    <input type="text" value="<? echo htmlspecialchars($value, ENT_QUOTES); ?>" />
    

    The ENT_QUOTES is optional and also encodes the single quote ' .

    I used $value since I'm not sure what exactly you have in the database (with or without quotes?) but it will sit in some kind of variable if you want to use it anyway, so, I called that $value.

    Since the above is a bit unwieldy I made a wrapper for it:

    // htmlents($string)
    function htmlents($string) {
      return htmlspecialchars($string, ENT_QUOTES);
    }
    

    So you can

    <input type="text" value="<? echo htmlents($value); ?>" />
    

    Not to be confused with the existing htmlentities(), which encodes all non-standard characters. htmlspecialchars() only encodes &, <, >, " and ', which is more appropriate for UTF8 pages (all your webpages are UTF8, right? ;-).

    0 讨论(0)
  • 2021-01-15 05:33
    <?php
    
    echo "<input type='text' value='{$foo}' />" ;
    
    ?>
    
    0 讨论(0)
  • 2021-01-15 05:34

    use urlencode or htmlspecialchars

    <a href="<?php echo urlencode($dburl)?>" title="<?php echo htmlspecialchars($dbvalue)?>">link</a>
    
    0 讨论(0)
  • 2021-01-15 05:40

    First, don't use short tags ('

    Next, your HTML is malformed because you've got an extra set of quotes. Since you seem to be taking the approach of embedding PHP into the HTML, then a quick fix is:

    <input type="text" value="<?php echo 'foo'; ?>" />
    

    ...although since this value is coming from your database it will be stored in a variable, probably an array, so your code should look more like:

    <input type="text" value="<?php echo $db_row['foo']; ?>" />
    

    For clarity, most programmers would try to eliminate switching between PHP parsed and non-parsed code either using a template system like smarty or....

    <?php
     ....
     print "<input type='text' value='$db_row[foo]' />\n";
     ....
    ?>
    

    (Note that

    1) when the variable is within double quotes with a block of PHP, the value is automatically substituted

    2) when refering to an associative array entry within a double quoted string, the index is NOT quoted.

    HTH

    C.

    0 讨论(0)
  • 2021-01-15 05:41

    You can use htmlentities to overcome this problem like so:

    <input type="text" value="<? echo htmlentities('"foo"'); ?>" />
    

    this will return

    <input type="text" value="&quot;foo&quot;" />
    

    avoiding any conflict with html.

    0 讨论(0)
提交回复
热议问题