I'm having a problem with an SQL query that works with mysql_query but not with db_query. I'm running MySQL 5.0. Here is a table I added:

CREATE TABLE `user_profile` (
`uid` int(10) unsigned NOT NULL default '0',
`company_name` varchar(60) default '',
`first_name` varchar(60) default '',
`last_name` varchar(60) default '',
`address` varchar(255) default '',
`city` varchar(60) default '',
`state` varchar(60) default '',
`zip_code` varchar(60) default '',
`practice_type` varchar(60) default '',
`phone` varchar(60) default '',
`fax` varchar(60) default '',
`enrollment_status` varchar(60) default '',
`graduation_year` int(11) unsigned default '0',
PRIMARY KEY (`uid`)
)

I get one row as expected with the following code used with mysql_query:
SELECT p.*, r.rid, u.name as user_name, u.created FROM users u INNER JOIN user_profile p ON u.uid = p.uid INNER JOIN users_roles r ON p.uid = r.uid WHERE (r.rid = 4 || r.rid = 5) AND (p.first_name LIKE "%blah%" OR p.last_name LIKE "%blah%")

But the following returns zero rows with db_query:
SELECT p.*, r.rid, u.name as user_name, u.created FROM {users} u INNER JOIN {user_profile} p ON u.uid = p.uid INNER JOIN {users_roles} r ON p.uid = r.uid WHERE (r.rid = 4 || r.rid = 5) AND (p.first_name LIKE "%blah%" OR p.last_name LIKE "%blah%")

I have to admit, I'm not a database expert, so if I'm doing something stupid, let me know. :)

Thanks,
Dave

Comments

Can you show the other part

Can you show the other part of your code? That looks like it should be fine, so it would seem that you probably have an error somewhere else in your code (for example how you accessing the rows after the query is run).

db_query adds parameter

db_query adds parameter substitution, so things like %d, %s are processed as arguments to the db_query call. A side effect is that the use of % in a query needs to be double so for example "%blah%" would become "%%blah%%". Personally though I would write is something like

$name = '%blah%';
$sql = "SELECT p.*, r.rid, u.name as user_name, u.created FROM {users} u INNER JOIN {user_profile} p ON u.uid = p.uid INNER JOIN {users_roles} r ON p.uid = r.uid WHERE (r.rid = 4 || r.rid = 5) AND (p.first_name LIKE '%s' OR p.last_name LIKE '%s')";
$results = db_query($sql, $name);

That's what the problem was!

That's what the problem was! Thanks nevets!

I'm building the query programatically, depending on which combination of filters the user selects. Otherwise I would do it the way you suggested.

Dave

All the more reason to do it the way nevets suggests. Otherwise you're leaving yourself wide open to injection attacks.