What Is The Best Way To Echo Results From The Database Into Html Code In Php?
Solution 1:
use urlencode
or htmlspecialchars
<ahref="<?phpecho urlencode($dburl)?>"title="<?phpecho htmlspecialchars($dbvalue)?>">link</a>
Solution 2:
You can use htmlentities to overcome this problem like so:
<inputtype="text"value="<?echo htmlentities('"foo"'); ?>" />
this will return
<inputtype="text"value=""foo"" />
avoiding any conflict with html.
Solution 3:
htmlspecialchars() basically, for example
<inputtype="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)functionhtmlents($string) {
return htmlspecialchars($string, ENT_QUOTES);
}
So you can
<inputtype="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? ;-).
Solution 4:
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:
<inputtype="text"value="<?phpecho'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:
<inputtype="text"value="<?phpecho$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.
Solution 5:
<?phpecho"<input type='text' value='{$foo}' />" ;
?>
Post a Comment for "What Is The Best Way To Echo Results From The Database Into Html Code In Php?"