/    Sign up×
Community /Pin to ProfileBookmark

AJAX PHP Mysql special characters problem

Hi

i am having an issue inserting data into mysql if the data has special characters. For example, if i try to add “john’s pencil”, it does not add it to my database. Here’s my code:

[CODE]
var text=textbox.value;
var xhr;
if (window.XMLHttpRequest) // Object of the current windows
{
xhr = new XMLHttpRequest(); // Firefox, Safari, …
}
else if (window.ActiveXObject) // ActiveX version
{
xhr = new ActiveXObject(“Microsoft.XMLHTTP”); // Internet Explorer
}
xhr.onreadystatechange = function(){
if(this.readyState == 4){
textbox.value=”Response Added”;
}
}
xhr.open(“GET”, “insert.php?user=”+user+”&text=”+text, true);
xhr.send(null); [/CODE]

textbox and user are set earlier, so they do exist when this is called.

and here is insert.php:

[CODE]<?php
$user=$_GET[‘user’];
$text=$_GET[‘text’];

$con=mysql_connect(“localhost”,$username,$password);
mysql_select_db($database,$con);

$query=”INSERT INTO responses VALUES(NULL,’$user’,’$text’);”;
mysql_query($query);

echo $user;

mysql_close($con);
?>
[/CODE]

I tried adding encodeURIComponent on the JS code, but that didn’t work.

The weird thing is that I can see the call made by ajax on firebug is:

[CODE]GET http://localhost/Website/insert.php?user=Guest&text=john%27s%20book[/CODE]

so I can’t figure out why the ‘ breaks it.

Thanks for the help

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@svidgenJan 05.2011 — Change
[code=php]$user=$_GET['user'];
$text=$_GET['text'];[/code]

To
[code=php]
$user=mysql_real_escape_string($_GET['user'], $con);
$text=mysql_real_escape_string($_GET['text'], $con);[/code]

And move the lines below the connection initialization.

Also, read up on magic quotes and protecting against SQL injection, particularly by passing all SQL parameters in PHP through mysql_real_escape_string().
Copy linkTweet thisAlerts:
@svidgenJan 05.2011 — To answer your question more directly, your example looks like this to MySQL:
[CODE]INSERT INTO responses VALUES(NULL,'Guest','john's book');[/CODE]
And that just won't work ... See my previous post and be sure to read up on SQL injection!
×

Success!

Help @alfehaieotasdh spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...