Monday, May 11, 2009

Handling single quotes in PHP and Javascript


We need to take additional care when dealing with quotes especially single quotes in web development.

We can use single quotes as well as double quotes for specifying attributes for HTML tags.

i-e We can use as below,

<a href="http://qualitypointtech.com">QualityPoint</a>

or we can use as below also,
<a href='http://qualitypointtech.com'>QualityPoint</a>

And also, in javascript also we can use both single quotes and double quotes.

i-e Both alert("Hi") and alert('Hi') are valid.
But we need to take care when using them.

Consider below scenario.

We are having set of images stored in a folder and we are having image names in database.

Assume that our requirement is to display image based on the image name when clicking a link "Click here to Display Image".

So, the HTML/javascript code can be written as below,

$name="qualitypoint";
<a href="#" onClick="displayName('<?php echo $name; ?>');">Click here to Display Image</a>

function displayName(strname)
{

document.getElementById("namediv").innerHTML="<img
src='"+strname+"'>";

}

Assume that the $name is having single quotes as below
$name="qualitypoint's logo";

In this case, we will get syntax error from browser because of this single quotes.

So, to avoid this syntax error we can escape the single quotes using escape character as below.
$name="qualitypoint's logo";
$name=str_replace("'", "\'",$name);

It will avoid syntax error. But, still the image may not display correctly.

Because, we need to escape the single quotes within javascript function also.

We have tried to escape it as similar to previous one using below code.
strname=strname.replace("'","/'");

But, it didn't work correctly. Because single quotes were unexpectedly replaced with question mark symbol (?).

We have tried to use the HTML Entity ". But it didn't work.
Finally, the entity "&#39;" worked correctly to display the images having single quotes in their name.

We had to replace the single quotes as below in the javascript function,

strname=strname.replace("'","&#39;");

After making these changes everything worked fine.

Similarly, we may face issues for inserting data into database table if the data is having single quotes.

Normally for inserting string with single quotes, we can replace the single quotes in the string with two single quotes before inserting them into the database.

More Articles...

No comments:

Search This Blog