...

View Full Version : mysql select where question



student
02-08-2007, 06:59 PM
hello,
i got another doubt,
as i have told you before i have a directory of websites in different categories.
when visitors search for some keyword, i have to search for it in titles, descriptions of websites.

the sql query is:
$sth = mysql_query("SELECT * FROM cb_urls WHERE title LIKE '%".addSlashes($keywords)."%' OR description LIKE '%".addSlashes($keywords)."%' ");

this query seaches all websites in all categories.

but i would like to search in only a particular category.
i have stored that category in a string $category.

now i want search results only in that particular category.
how can i do it.
thank you.

homerUK
02-08-2007, 07:04 PM
just add



where category ='".$category."'


so it'd be



$sth = mysql_query("SELECT * FROM cb_urls WHERE title LIKE '%".addSlashes($keywords)."%' OR description LIKE '%".addSlashes($keywords)."%' WHERE category='".$category."'");

student
02-08-2007, 07:09 PM
thanks for a quick reply,
can i use WHERE clause twice in the same query?
thanks

homerUK
02-08-2007, 07:12 PM
yeah you can put an AND statement in...



WHERE category = '".$category."' AND somethingelse = '".$somethingelse."'


(you can use OR as well there)
eg:



WHERE category = '".$category1."' OR category = '".$category2."'

student
02-08-2007, 07:45 PM
i have to search for keywords in title and description only when category = $category.

can i use this query?

$sth= mysql_query("SELECT * FROM table WHERE category='".addSlashes($category)."' AND title LIKE '%".addSlashes($keywords)."%' OR category='".addSlashes($category)."' AND description LIKE '%".addSlashes($keywords)."%'");

this code is working,
but is it efficient? is there any better method of coding this?
thanks

neomaximus2k
02-09-2007, 12:24 PM
That code would work but to achieve what you want you need to add brackets to the code as bellow


<?php

$sth= mysql_query("SELECT * FROM table WHERE (category='".addSlashes($category)."' AND title LIKE '%".addSlashes($keywords)."%') OR (category='".addSlashes($category)."' AND description LIKE '%".addSlashes($keywords)."%')");
?>

that way it will do either the first category=$category and title like blah OR category = $category and desciption like $keywords

... actually come to think of it the code should be


<?php

$sth= mysql_query("SELECT * FROM table WHERE category='".addSlashes($category)."' AND (title LIKE '%".addSlashes($keywords)."%') OR description LIKE '%".addSlashes($keywords)."%')");
?>

That way you are saying category = $category but the keyword can be in title OR description



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum