PHP, Escaping Apostrophes

53 views
Skip to first unread message

Warren Michelsen

unread,
Aug 16, 2010, 10:31:30 AM8/16/10
to Web Authoring List
In response to a search of a mySQL database, I loop through the results like this:

while ($row = mysql_fetch_object($result))
{ // while
$theID = $row->ID;
$theName = $row->ItemName;
echo "<input name=\"ItemID\" type=\"radio\" value=\"$theID\" onChange=\"MyForm.NewValue.value='$theName'\">$theName<br>\n";
} // while


This produces something like:
<input name="ItemID" type="radio" value="124" onChange="MyForm.NewValue.value='Anger Management'">Anger Management<br>
<input name="ItemID" type="radio" value="151" onChange="MyForm.NewValue.value='Atonement'">Atonement<br>

which is fine and properly populates the NewValue field with the value of the item selected by the radio button.

A problem arises, however, when the result includes an apostrophe as in:

<input name="ItemID" type="radio" value="112" onChange="MyForm.NewValue.value='All the President's Men'">All the President's Men<br>
<input name="ItemID" type="radio" value="376" onChange="MyForm.NewValue.value='Dead Men Don't Wear Plaid'">Dead Men Don't Wear Plaid<br>

Any apostrophes in $theName need to be escaped for JavaScript to work properly.

Is there a php function I can use on $theName to escape any apostrophes such that it results in:

<input name="ItemID" type="radio" value="112" onChange="MyForm.NewValue.value='All the President\'s Men'">All the President's Men<br>
<input name="ItemID" type="radio" value="376" onChange="MyForm.NewValue.value='Dead Men Don\'t Wear Plaid'">Dead Men Don't Wear Plaid<br>

?

Mickey

unread,
Aug 16, 2010, 10:41:50 AM8/16/10
to Web Authoring List

Found it. "addslashes" built right into php.

At 7:31 AM -0700 8/16/10, Warren Michelsen sent email regarding PHP,
Escaping Apostrophes:

Reply all
Reply to author
Forward
0 new messages