Problem escaping php variable
565
I'm having trouble escaping the PHP variable inside the getItems function:
while($row = mysql_fetch_array( $data ))
{
echo "<div class='favorite'>";
echo "<div style='display: inline;'>".$row['Item']."</div>";
if ($row['UID'] = $uid) {
echo "<div id='unlock'>Info</div>";
} else {
echo "<div id='unlock' onclick='getItems('".$row['Item']."')'>Unlock</div>";
}
echo "</div>";
}
When rendered (is render the word?) anyway, when I see it on my site it says:
onclick="getItems(" whatever')'
What am I doing wrong?
You can see the code here: http://www.chusmix.com/game/insert/get-items.php?user=19
Answer
Solution:
Your problem is that your attribute values are surrounded by single quotes, but you're also using single quotes in your javascript.
You'll have to use double quotes in your javascript. However, since the whole string (in PHP) is surrounded by double quotes, you'll have to escape them. Hence:
Or like this:
To clarify what the curly braces do (from the PHP docs):
To further explain, let's say we have the following scenario:
What I'm trying to get is:
Apples are my favorite fruit
. However, this won't work. PHP will instead be looking for a variable called$names
, and when it doesn't find it, it'll complain.So, to remedy this, we can surround our variable in curly braces:
Great! Now PHP will know where the variable name ends and the string starts.
On a side note: You might consider switching to double-quoting your attributes, since the way you do it now is not valid xHTML (unless you don't care).
Answer
Solution:
Yes, there is a problem with your quotes. It should be this:
The problem is that your opening quotes for
onclick
and the quotes around the function arguement have to be a different kind of quote.This is much easier though to do with html and then just insert the variable like this:
Doing things this way instead of echoing HTML when possible will save you tons of time and confusion, and you won't have to worry about all the escaping of quotes
Answer
Solution:
The
'
inside onclick is closing the onclick itself. Change it to:That way, in JS, it uses a different type of quote.
Even better... you can leave PHP, and have one less type of quote to worry about.
Answer
Solution:
or like so:
If I had to do this, it would have looked like:
Answer
Solution:
try the following . edit: changed to make sure quotes were escaped correctly