Escaping output data from mysql?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
junestag
Forum Commoner
Posts: 39
Joined: Tue Sep 18, 2007 5:14 pm
Location: Alaska
Contact:

Escaping output data from mysql?

Post by junestag »

I'm trying to output some mysql data via php INSIDE some javascript (jquery) code. Unfortunately some of the data in my php variable $course_block which goes inside a <SELECT> element contains apostrophes that are anathema to my jquery code and so nothing shows correctly.

My question is pretty basic: how (or can) I get rid of any apostrophe characters coming out of my MySQL database before I even use the data in my JavaScript?

Here's the code I'm using to get the data and to input it into JavaScript (it all works):

$sql = "SELECT title, subject, coursenum, section, crn, instructor, credits, price FROM catalog ORDER BY subject,coursenum";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
$subject = $row['subject'];
$coursenum = $row['coursenum'];
$section = $row['section'];
$crn = $row['crn'];
$title = $row['title'];
$instructor = $row['instructor'];
$credits = $row['credits'];
$price = $row['price'];
$course_block .= "<option value=\"$subject-$coursenum-$section-$crn-$title-$instructor-$credits-$price\">$subject $coursenum- $title- Instructor: $instructor- Section: $section- Credits: $credits- Price: \$$price</option>";
}

<script type="text/javascript">
var count = 0;
$(function() {
$('p#add_field').click(function() {
count += 1;
$('#container').append('<select id="field_' + count + '" name="fields[]' + '"> <?php echo "$course_block"; ?> ) </select>');
});
});

</script>
Virvo
Forum Newbie
Posts: 3
Joined: Wed Nov 25, 2009 4:20 am

Re: Escaping output data from mysql?

Post by Virvo »

I dont think you want to "get rid" of them, but rather just escape them... something as simple as...

$course_block = str_replace("'", "\'", $course_block);
Post Reply