#1
  1. Plays with fire
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Aug 2003
    Location
    Barsoom
    Posts
    1,133
    Rep Power
    144

    PDO and MySQL LIKE


    Hi--

    Can anyone tell me why this doesn't work:

    Code:
    	$field="username";
    	$option="del";
    
    	$sql="SELECT * FROM x WHERE ? LIKE ?";
    	$sth=$dbh->prepare($sql);
    	$sth->execute(array($field,"%".$option."%"));
    If I type the full query into PHPMyAdmin it works fine, but running it this way from my page I get nothing back, not even and error, but I should see 2 results.

    Any ideas?

    I've always had problems with PDO and LIKE.

    Thanks!
    “Be ashamed to die until you have won some victory for humanity.” -- Horace Mann

    "...all men are created equal." -- US Declaration of Independence
  2. #2
  3. Plays with fire
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Aug 2003
    Location
    Barsoom
    Posts
    1,133
    Rep Power
    144
    Oh, crap. Never mind. Can't use a field name as a parameter.

    It never fails. As soon as I post a question, I solve it myself. Hopefully someone else can learn from this.
    “Be ashamed to die until you have won some victory for humanity.” -- Horace Mann

    "...all men are created equal." -- US Declaration of Independence
  4. #3
  5. Lazy Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,279
    Rep Power
    9645
    The error would happen after the prepare(), $sth would be false, and $sth->execute would cause a fatal error/white page of death.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2016
    Posts
    87
    Rep Power
    5
    ^^^ Actually, this wouldn't throw an error (just tested). The left-hand side of the LIKE is an expression. The resultant - 'a string value' LIKE pattern would just produce a true or false result and either match everything or nothing in the table. In fact, the mysql documentation uses literal string values in the examples - SELECT 'David!' LIKE 'David_';

    Comments on this post

    • requinix agrees
  8. #5
  9. Lazy Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,279
    Rep Power
    9645
    Ah, that's right. I was rather surprised the fatal error went unnoticed...

IMN logo majestic logo threadwatch logo seochat tools logo