function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

How to handle special characters in query in PHP

I've gotten pretty proficient at escaping characters as needed, but this time the problem is in a query itself.


Here's the basic code. It's using the PHP toolkit:


  $userid = $_POST["userid"];


  $mySforceConnection = new SforcePartnerClient();
  $mySoapClient = $mySforceConnection->createConnection('partner.wsdl.xml');
  $mylogin = $mySforceConnection->login($username, $password);


  $userid = htmlentities($userid);


  $query = "select id from contact where User_ID__c ='$userid'";

  $response = $mySforceConnection->query($query);
  $queryResult = new QueryResult($response);


It's the query, that's breaking because there's a backslash ("\") in the userid ("alan\katz").


Unfortunately, I can't control the userids, so I'm stuck with it. 


Here's the error:

ERROR at Row:1:Column:48 line 1:48 mismatched character '\' expecting '''
I tried using htmlentities, but that doesn't seem to fix it.
Any ideas? Please, I'm a bit desperate on this one!

Got it!!!


Used PHP addslashes() and the query is no longer "malformed".


Thanks to anyone who took the time to read this!


Make sure you also replace any XML predefined entities with their character codes also, or you could run into errors there too.