April 13, 2012

Wildcard for WHERE?

Question by Sam Clark

I want to setup code that does this: (* is wildcard)

SELECT * FROM * WHERE * CONTAINS '$search-query';

What MYSQL code can I use to acheive this.

Answer by Starx

There is a project called anywhereindb which can do what you want.


I am not going to create a full solution, its going to take a long time, but, I am going to create an example of what you would called

SELECT * From `tablename` WHERE * CONTAINS `$search_query`

First, lets extract the fields

$fields = array();
$query = "SELECT * FROM `yourtable` LIMIT 1;";
$result = mysql_query($query);
while ($i < mysql_num_fields($result)) {
    $info = mysql_fetch_field($result, $i);
    $fields[] = $info -> name;
}

Now prepare your query

$query = "SELECT * FROM `table` WHERE";
foreach($fields as $index => $field) {
    $fields[$index] = $field." CONTAINS '$search_query'"
}
$query .= implode(" and ", $fields);
//Finally query
$result = mysql_query($query);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!