简体   繁体   中英

How use multiple conditions in xpath query?

 $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

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 .

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

(@sender ='".$from."

There's nothing wrong with your general approach.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM