2
 $elements = $xpath->query(
   "//message[(@sender ='".$from." and @receiver = '".$username."') or
   (@receiver='unread' and @sender = '".$username."')]"
  );

Whats the problem with this code? I need something like this SELECT data WHERE ((sender == from AND receiver = username)OR(sender == username AND receiver = from)) from my xml file

0

3 Answers 3

4

Use sprintf instead. It's less messy and errors are more easy to spot.

$query = sprintf(
    '//message[
        (@sender = "%1$s" and @receiver = "%2$s") or
        (@receiver="unread" and @sender = "%2$s")
    ]',
    $from,
    $receiver
);

Also, make sure to sanitize $from and $receiver to prevent XPath Injection attacks.

Sign up to request clarification or add additional context in comments.

Comments

2

You're missing a closing single quote after this portion:

(@sender ='".$from."

There's nothing wrong with your general approach.

2 Comments

thanks.. i wasted two hours by analyzing this error and failed to debug
@EbinPaulose - It's an easy mistake to make. It's a good idea to print out the constructed value early on (or use sprintf as others have suggested). It makes errors easier to spot.
1

One of the problems with your code is that you're exposing yourself to injection attacks. Do you really trust $from and $username to be simple strings? Rather than building a query using string concatenation, it's much safer (and faster) to set up a parameterized query in which the parameters are supplied externally. I've no idea if the PHP API you are using allows you to do that.

1 Comment

unfortunately, none of the native XML APIs in PHP allow parameterized queries. There is a couple of 3rd party libs though, which compensate with their own implementations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.