0

I have function for getting the user data from database

    function getUser($usernameOrEmail) {
        global $db;
        $stm = $db->prepare("SELECT * FROM users WHERE username = :userData OR email = :userData");
        $stm->execute([ ":userData" => $usernameOrEmail ]);
        $row = $stm->fetchAll(PDO::FETCH_ASSOC);
        return ($row != null) ? $row[0] : false;
    }

The problem is when I pass username with spaces in it, for example "John Doe" then I am always getting "false" as a result even if I have record with that username in database. But if I try just to pass for example "John" and I have that record in db also, everything is fine... What am I doing wrong?

xcentric
  • 41
  • 5
  • Are you sure `SELECT username FROM users WHERE username='John Doe'` works, and that you're not inadvertently passing in `"John%20Doe"`? – tadman Apr 06 '17 at 18:32
  • I am 100% sure that I am passing string 'John Doe' because even when I try to hardcode it it doesn't work. – xcentric Apr 06 '17 at 18:34
  • 1
    Simple: you can't reuse the same placeholder name in PDO. You need to rename one of them and then add another named bind. I almost popped this in as an answer; I should have lol Edit: @tadman am surprised you didn't catch that ;-) – Funk Forty Niner Apr 06 '17 at 18:51
  • But if that is true then it shouldnt work just with one word parameter without spaces and it works. – xcentric Apr 06 '17 at 18:52
  • @Fred-ii- I don't use PDO so much as advocate for it as a base-line for most people to use. It's got some fundamental flaws, like this, which really should be patched. – tadman Apr 06 '17 at 18:56
  • Would `:userData IN (username, email)` work? – tadman Apr 06 '17 at 18:56
  • @tadman Oh, I didn't know. Sorry, I took it that you did know. I should not have been so presumptuous. – Funk Forty Niner Apr 06 '17 at 18:57
  • You can use the same parameter name multiple times if `ATTR_EMULATE_PREPARES` is on. – Will B. Apr 06 '17 at 18:59
  • @Fred-ii- It's one of those things that's easy to forget. PDO has a lot of irritating quirks and I'm not always keeping them front of mind. I only recommend it since it has fewer quirks than the alternatives. – tadman Apr 06 '17 at 19:01
  • @tadman I take it that you don't visit YCS's website neither ;-) – Funk Forty Niner Apr 06 '17 at 19:01
  • @Fred-ii- Not familiar with what that is. – tadman Apr 06 '17 at 19:02
  • @xcentric What does `var_dump($stm->execute([ ":userData" => $usernameOrEmail ])); exit;` return? – Will B. Apr 06 '17 at 19:16

0 Answers0