Monday, April 23, 2018

php - How can I escape single quotes in this scenario?

I have a page which makes a jquery call to an api to receive multiple wikipedia urls. I then
extract the article names from the url (i.e. get science from http://en.wikipedia.org/science etc), add single quotes (') to each one, string them together and finally send them to a php page, which makes a mysql select * from MyTable where title in('name1','name2','name3','name4') call. The problem arises when the article name already has a single quote in it (i.e. "Hick's law"), as it breaks the where in single quotes. Here's the code I'm using:



$.getJSON('http://ajax.googleapis.com/ajax/services/search/web?q=keyword site:en.wikipedia.org&rsz=8&v=1.0&callback=?',
function (r) {
var urls1="";
$.each(r.responseData.results, function(i, item) {
var thisurl = (i==0) ? "'" + item.url.substring(item.url.lastIndexOf('/') + 1) + "'" : ",'" + item.url.substring(item.url.lastIndexOf('/') + 1) + "'";
urls1 += thisurl.replace(/_/g,'%20');

});});
$('#quotes').html($('
').load('pr.php?s='+urls1 +' #quotes', function() {}


I'm adding the single quotes to the article names so the string should be all ready to go for the mysql where in.



So to recap, the steps are as follows:




  1. Make an api call and get multiple Wikipedia urls,

  2. get the article name from each url,

  3. add them to the urls1 string while replacing underscores with spaces

  4. send the urls1 string via ajax to the pr.php page.

  5. In pr.php I do the following: "SELECT * FROM MyTable WHERE title in".$_GET['s']



I tried doing mysql_real_escape_string($_GET['s']) but that didn't work.



I'm now trying to escape any single quotes inside the article names so the where in doesn't break, but it's not working. I tried changing the above to



var thisurl=(i==0) ? "'"+item.url.substring(item.url.lastIndexOf('/') + 1).replace(/'/g, "\'")+"'":",'"+item.url.substring(item.url.lastIndexOf('/') + 1).replace(/'/g, "\'")+"'";


But it didn't work. Any ideas?



TIA!

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...