tags:

views:

32

answers:

2

I'm trying to do a friend search app. So to do that I'm using regular expressions like:

SELECT ... 
 WHERE firstname REGEXP $firstname

And the $firstname variable is a string - for example:

(ch|k)ris

But for some reason it does not work. maybe the ( | ) doesn't work in MySQL?

What can I use instead of that operator to do the same thing?

A: 

This:

SELECT * 
  FROM users
 WHERE firstname REGEXP '(ch|k)ris'

...works fine for me on MySQL 5.1.49, using:

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB

INSERT INTO users 
VALUES (DEFAULT, 'Andrew'), 
       (DEFAULT, 'Chris'), 
       (DEFAULT, 'kris')

In my testing via MySQL Workbench, I get a 1064 error if the regex is not enclosed in single quotes. You'll need to provide information about how this isn't working for you -- is there actually data in the table that this query would return?

OMG Ponies
My query in mysqli php: SELECT ... FROM users WHERE id NOT IN($alreadyfriend) AND firstname REGEXP $firstname;
is that right ?
@user484957: The only thing I'm unsure of is if the regex will be enclosed in quotes, but IME you'll get a 1064 error if it isn't so check that you aren't suppressing errors.
OMG Ponies
I don't get any errors.. maybe because it's an ajax call... idk... how can I make sure it is enclosed in quotes? should i use a function to convert it to string or somthing?
@user484957: Print out the variable containing the SQL statement to screen before it's executed.
OMG Ponies
+1  A: 

in PHP modify your line to this:

$query = "SELECT ... FROM users WHERE id NOT IN($alreadyfriend) AND firstname REGEXP '$firstname'"; //notice the single quotes
ajacian81