PDA

View Full Version : php question with sql query..


Pyscho
02-27-2005, 01:51 PM
$name = $_POST['p_name'];

if (!empty($name)) {
$result = "select * from product where name LIKE '$name'";
}


What I need is when the user types something like c* in the edit box, it will return all records where the product Name begins with c..

At the moment, I have it like if I enter c% in the edit box, then it will returns records where the name begins with c. BUT I don't want this, I need it to be so the user enters <letter*> (e.g. a*) and then it processes the query to return all recrds where name begins with <letter>

So, what im stuck on is how to get the input, e.g. c*, to something like
select * from product where name LIKE 'c%'
..thanks in advance.

delinear
02-27-2005, 02:06 PM
Hmm, try this...

if (!empty($name)){
for($i=0; $i <= strlen($name); $i++){
if(substr($name, -$i, -($i - 1)) == '*'){
$likeset = 'true';
$name = substr($name, 0, -$i);
}
}
if($likeset != 'true'){
$result = "select * from product where name='$name'";
} else {
$result = "select * from product where name LIKE '$name'";
}
}
It should count backwards through the string $name looking for a *. If it finds one it strips out the * and any crap after it so you are left with everything before the *. It then sets $likeset to true which prompts a query using LIKE, if there is no * character it just uses a standard matching query on $name.

Fou-Lu
02-27-2005, 02:12 PM
Whoa. Lost me there, seems like your post says you have what your looking for.
So, you have an input form, user enters c*. You want the '*' to match as a like '%' correct, without having to type in the '%'?
str_replace() is what you want:

$name = htmlspecialchars($_POST['p_name']);

// $name = 'c*', change it:
$name = str_replace('*', '%', $name);

if (!empty($name)) {
$result = "select * from product where name LIKE '$name'";
}

This will also allow you to search partials, which would be nice:
*bob* matches anything with 'bob' in the name, b* matches anything beginning with 'b'. Should be ok this way, I don't believe that the * or % will be translated in anyway, which is good.

Pyscho
02-27-2005, 02:20 PM
Fou-Lo .. absolutely brilliant.. thank mate.

Kurashu
02-27-2005, 02:59 PM
You will probably also want to make your serach case insensitive by using ILIKE