Waqas
Waqas

Reputation: 335

Searching substring in a row of mysql?

I have column name code_color which have combination of number and letters like 009grey so the problem is I am asking a user for color only which is grey so how do I search only the color string? here is the query

 "SELECT * FROM shoes WHERE name = '$searchKeyword' AND code_color = '$color' AND sex = '$gender' ";

where code_color have the strings like that 009grey, 008red etc and color from user would be grey or any other color. How can I do it ?

Edit

What if it is stored in DB as m and we get from user is $_POST['sex'] which contains male how can we search for it ? LIKE %% methods doesn't seems to apply here !

Upvotes: 0

Views: 73

Answers (4)

phsaires
phsaires

Reputation: 2378

Remove all numbers from string with regex

$color = preg_replace('/[^\\/\-a-z\s]/i', '', $color);
"SELECT * 
FROM shoes WHERE name = '$searchKeyword' 
AND code_color ='$color' 
AND sex = '$gender' ";

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173522

It seems you want to skip the first three digits of code_color before attempting the search

SELECT * 
FROM shoes 
WHERE name = :kw AND SUBSTRING(code_color, 4) = :color AND sex = :gender

The :<name> notation is used to denote parameter placeholders as those used in prepared statements.

Upvotes: 0

Sam
Sam

Reputation: 611

You can do something like

SELECT * FROM shoes WHERE code_colour LIKE '%$color'

keep in mind if you are pasting variables directly into your SQL query you are vulnerable to SQL Injection - http://bobby-tables.com/php.html

Upvotes: 2

Jessica
Jessica

Reputation: 7005

"SELECT * 
FROM shoes WHERE name = '$searchKeyword' 
AND code_color LIKE '%$color%' 
AND sex = '$gender' ";

Your code is open to injections however, you should look into using parameterized queries. (Using MySQLi or PDO)

Upvotes: 2

Related Questions