Search code examples
phpmysqlsql-like

MySQL Like query but not like other


    $SQL = "SELECT * FROM `user_posts` WHERE (`post` LIKE '%@".$user."%')";

For instance, if my username is @Jake, it will show any post that has @Jake in it. But it will also do for instance, @Jake11, it will also show. How can I fix this?


Solution

  • You might consider using some sort of regular expression instead of LIKE '%...%'.

    An example might be:

    ... WHERE `post` REGEXP '@" . mysql_real_escape_string( $user ) . "[[:>:]]'"
    

    The [[:>:]] matches on a right word boundary. As pointed out by Bill Karwin, there's no need for a left-hand boundary pattern in this case as there is an implied word boundary at the @ character. (Indeed, you can't have a left-boundary to the left of a non-word character.)

    (I'm sure others will comment on your possible exposure to SQL injection attack too.)