/    Sign up×
Community /Pin to ProfileBookmark

search string in mysql

Can someone provide me a sample code how I can have a “search” field search for any keyword that matches my records in my database.

I have a list of agencies we fund, they have a 25 word description column. If someone searches for any word and it matches that of the “description” column list records by ID desc.

Is this possible to do a simple search query? find word and/or and list records, otherwise return sorry, no records showing that keyword.

Thanks

to post a comment
PHP

35 Comments(s)

Copy linkTweet thisAlerts:
@NogDogOct 27.2005 — [code=php]
$search = $_POST['search_string'];
$query = "SELECT * FROM table_name WHERE description LIKE '%$search%'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
# echo columns of interest in desired sequence and format
}
[/code]
Copy linkTweet thisAlerts:
@d_brandusaauthorOct 28.2005 — How do I add "name" into there, either name or description columns, they might search the description of the organization or the name of itself.
Copy linkTweet thisAlerts:
@NogDogOct 28.2005 — [code=php]
$query = "SELECT * FROM table_name WHERE description LIKE '%$search%' OR name LIKE '%$search%'";
[/code]
Copy linkTweet thisAlerts:
@d_brandusaauthorOct 28.2005 — Thanks, I will try that.
Copy linkTweet thisAlerts:
@d_brandusaauthorOct 28.2005 — Okay, it works but with some search problems. Is there a way to make it NOT case-sensitive. For example, I will search for family, and records appear, but if I'm searching for an agency called Family it won't find unless I make the "f" capitals. is there a way to force it. Also, if I put "spaces" in between the words it won't find any at all. Is there also a way to say, if there is a space in between the words, take either or both words and try to find a match. First try to find a match for the full search, if nothing then search for each word separately without being case sensitive.
Copy linkTweet thisAlerts:
@NogDogOct 28.2005 — Not tested, so no guarantees:
[code=php]
# convert to upper case, trim it, and replace spaces with "|":
$search = strtoupper(preg_replace('/s+/', '|', trim($_POST['search_string'])));
# create a MySQL REGEXP for the search:
$regexp = "REGEXP '^.*($search).*$'";
$query = "SELECT * FROM table_name WHERE UPPER(description) $regexp " .
"OR UPPER(name) $regexp";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
# echo columns of interest in desired sequence and format
}
[/code]
Copy linkTweet thisAlerts:
@d_brandusaauthorOct 28.2005 — That workes fine but I realized on error. Say I put red cross, it will find everything word that has red within it, not a specific word. Its finding anything that has red in it, for example: Redding, Freddy...is there a way to say only ifs a "word" not the letters within it.
Copy linkTweet thisAlerts:
@NogDogOct 28.2005 — Give this a shot (said with a tone of uncertainty):
[code=php]
$regexp = "REGEXP '^.*[[:<:]]($search)[[:>:]].*$'";
[/code]
Copy linkTweet thisAlerts:
@d_brandusaauthorOct 31.2005 — It doesn't error out but it doesn't find any more data, it just won't return results.
Copy linkTweet thisAlerts:
@NogDogOct 31.2005 — Maybe...
[code=php]
$regexp = "REGEXP '[[:<:]]($search)[[:>:]]'";
[/code]
Copy linkTweet thisAlerts:
@d_brandusaauthorOct 31.2005 — No..same...thanks so much for trying to help NogDog, you have know idea how much I appreciate getting this far!!!
Copy linkTweet thisAlerts:
@NogDogOct 31.2005 — Tried this test on a DB on my PC, seemed to work pretty well. Just posting here for you to see what I'm trying in a complete context.
[code=php]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang='en'>
<head>
<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>
<title>Page title</title>
<style type="text/css">
table {
border-collapse: collapse;
border: solid 1px black;
}
td {
padding: 2px 6px;
border: solid 1px black;
}
</style>
</head>
<body>
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'>
<p>Search for: <input type='text' name='search' size='20' maxlength='64'></p>
<p><input type='submit' value='Search'></p>
</form>
<?php
if(isset($_POST['search']))
{
$connx = mysql_connect('localhost', '*****', '*****') or die("connx");
$db = mysql_select_db('test') or die(mysql_error());
# convert to upper case, trim it, and replace spaces with "|":
$search = (ini_get('magic_quotes_gpc')) ? stripslashes($_POST['search']) :
$_POST['search'];
$search = mysql_real_escape_string($search);
$search = strtoupper(preg_replace('/s+/', '|', trim($_POST['search'])));
# create a MySQL REGEXP for the search:
$regexp = "REGEXP '[[:<:]]($search)[[:>:]]'";
$query = "SELECT * FROM users WHERE UPPER(description) $regexp OR ".
"name $regexp";
$result = mysql_query($query) or die($query . " - " . mysql_error());
echo "<table>n";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
foreach($row as $key => $value)
{
echo "<td>$value</td>";
}
echo "</tr>n";
}
}
?>
</body>
</html>
[/code]
Copy linkTweet thisAlerts:
@d_brandusaauthorOct 31.2005 — That did it, thanks so much!
Copy linkTweet thisAlerts:
@phpnstuffJun 22.2006 — The above code works great, is it possible to allow a part of the search string with one column only. The way the code is setup it looks for "whole" words. I have 1 column thats 5 digits for customer codes, but some are 4 digits. The 4 digits would normally have a 0 infront like this 01234 but its 1234, so If I search for 1234 it finds the record, if I search for 01234 it doesn't find the record. Can I tell it on column 'bn2' to allow a fragment of the code to work?
Copy linkTweet thisAlerts:
@GertKOct 16.2013 — Hi, I have used the above code created by NogDog (and below):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"


"http://www.w3.org/TR/html4/strict.dtd">

<html lang='en'>

<head>

<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>

<title>Page title</title>

<style type="text/css">

table {

border-collapse: collapse;

border: solid 1px black;

}

td {

padding: 2px 6px;

border: solid 1px black;

}

</style>

</head>

<body>

<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'>

<p>Search for: <input type='text' name='search' size='20' maxlength='64'></p>

<p><input type='submit' value='Search'></p>

</form>

<?php

if(isset($_
POST['search']))

{

$connx = mysql_connect('localhost', '*****', '*****') or die("connx");

$db = mysql_select_db('test') or die(mysql_error());

# convert to upper case, trim it, and replace spaces with "|":


$search = (ini_get('magic_quotes_gpc')) ? stripslashes($_POST['search']) :

$_
POST['search'];

$search = mysql_real_escape_string($search);

$search = strtoupper(preg_replace('/s+/', '|', trim($_POST['search'])));

# create a MySQL REGEXP for the search:


$regexp = "REGEXP '[[:<:]]($search)[[:>:]]'";

$query = "SELECT * FROM users WHERE UPPER(description) $regexp OR ".

"name $regexp";

$result = mysql_query($query) or die($query . " - " . mysql_error());

echo "<table>n";

while($row = mysql_fetch_assoc($result))

{

echo "<tr>";

foreach($row as $key => $value)

{

echo "<td>$value</td>";

}

echo "</tr>n";

}

}

?>

</body>

</html> [/QUOTE]



Add my database and its working fine. Anyway I want to change some of the options. Right now it say:
echo "<td>$value</td>";

}
[/QUOTE]



Is it possible to change it so it just take out the infomations from the string that I want show? Means right now it shows everything in the string, but I only want the search to show the "Name" and "Description" from the string and not all the other info that is saved in the string like "adresse","phonenumber", "staff" and so on....


Is the above codes the right to use og should I use something else?

Please advice - THANKS
Copy linkTweet thisAlerts:
@GertKOct 16.2013 — The above code from NogDog work more than perfect. Anyway when you do a search using the codes given by NogDog it show the complete string from the database as the result.

Is it somehow possible to choose what part to be showed? Like If I only want to show the column “name” and “description” and want to hide the column “address”, “phonenumber”, “staff” and so one….

Hope someone can help or come with some other suggestions for creating this seach.

THANKS
Copy linkTweet thisAlerts:
@NogDogOct 16.2013 — Instead of doing the foreach() loop, just pick out the elements you want to display in whatever format you want.

PS: If you wrap your PHP code in [noparse][code=php]...[/code][/noparse] tags (instead of "quote" tags), it will be much easier for us to read.
Copy linkTweet thisAlerts:
@GertKOct 16.2013 — Hi NogDog,

Thanks for the fast reply. Im not sure what you mean. Can you help me write the code correct. Right now it say:

[code=php]
echo "<table>n";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
foreach($row as $key => $value)
{
echo "<td>$value</td>";
}
echo "</tr>n";
}
[/code]


I think you want me to change something here:'

[code=php]
foreach($row as $key => $value)
[/code]



But im not sure what to write. Can you help me?
Copy linkTweet thisAlerts:
@NogDogOct 16.2013 — Right, instead of doing the foreach, just explicitly output those elements that you want:
[code=php]
echo "<table>n";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>{$row['some_field']}</td>";
echo "<td>{$row['some_other_field']}</td>";
echo "</tr>n";
}
[/code]
Copy linkTweet thisAlerts:
@GertKOct 16.2013 — Hi NogDog,

This is perfect - WORKING. Thanks you so much ?

Another question that I hope you will help me with. Is it possible to seach in to different tables. Right now the script just search in one table:
[code=php]
# create a MySQL REGEXP for the search:
$regexp = "REGEXP '[[:<:]]($search)[[:>:]]'";
$query = "SELECT * FROM users WHERE UPPER(description) $regexp OR ".
"name $regexp";

[/code]



The above search in the table "users" but is it possible to search in both table "users" and a table called "staff"?

If yes, is it then also possible to search in different column i that table?

If possible can you tell me the codes, as you just did?

Thanks for all your help.
Copy linkTweet thisAlerts:
@NogDogOct 16.2013 — Depending on what you want to do and how the tables are related, you probably either want to do a JOIN or a UNION.

PS: Don't be offended by the "let me google that for you" links, I just enjoy using that from time to time. ?
Copy linkTweet thisAlerts:
@GertKOct 16.2013 — I See, What is the different on the join and Union?
Copy linkTweet thisAlerts:
@GertKOct 16.2013 — And, what do you suggest?
Copy linkTweet thisAlerts:
@NogDogOct 16.2013 — Without knowing exactly what the functional requirement is, I have no way of knowing which is appropriate. Joins are at the heart of the "relational" part of "relational databases". Union is a convenient way to query two separate tables for the same sort of data (which can sometimes be an indicator that your database design is not well normalized). I was hoping to spur you on to reading some of the tutorials so that you understand not just what to do but also why, as opposed to just writing code for you.
Copy linkTweet thisAlerts:
@GertKOct 16.2013 — Hi Again NogDog,

I found out that as for now I dont need to search in 2 tables.

Anyway I would like if it was possible to create a text saying "No search result found" when the search did not find anything. How do I add that to my codes. Can you give me the codes?

Please give me, as last time compleat code so I can copy and past it to the codes. I really hope you can help with this part ?
Copy linkTweet thisAlerts:
@NogDogOct 16.2013 — Use [url=http://php.net/mysql_num_rows]mysql_num_rows[/url]() in an if() statement to test for a result of 0.
Copy linkTweet thisAlerts:
@GertKOct 17.2013 — hmmm, Im not good at coding so Ihave no idea of how or where to add the code. When I do like this it dont Work:
[code=php]
<?php
if(isset($_POST['search']))
{
$connx = mysql_connect('localhost', 'cms_main', ',J4(tgM2X.(~') or die("connx");
$db = mysql_select_db('cms_main') or die(mysql_error());

# convert to upper case, trim it, and replace spaces with "|":
$search = (ini_get('magic_quotes_gpc')) ? stripslashes($_POST['search']) :
$_POST['search'];
$search = mysql_real_escape_string($search);
$search = strtoupper(preg_replace('/s+/', '|', trim($_POST['search'])));

# create a MySQL REGEXP for the search:
$regexp = "REGEXP '[[:<:]]($search)[[:>:]]'";
$query = "SELECT * FROM galleries WHERE UPPER(keywords) $regexp OR ".
"name $regexp";
$result = mysql_query($query) or die($query . " - " . mysql_error());

mysql_num_rows() in an if() statement to test for a result of 0.

echo "<table>n";
while($row = mysql_fetch_assoc($result))

{
echo "<tr>";
echo "<td><img src=../thumbs/photos/{$row['folder']}/{$row['date']}-{$row['num']}/{$row['thumbimage']} border=1></td>";
echo "<td>{$row['name']}</td>";
echo "<td>{$row['date']}</td>";
echo "<td><a href=../members/viewgallery.php?id={$row['id']} target=blank>View Photoset</a></td>";
echo "</tr>n";
}

}
?>

[/code]


Can you please let me know the codes where this should be add so it will Work. THANKS
Copy linkTweet thisAlerts:
@GertKOct 21.2013 — Hi NogDog,

Cann you please help me. You told me that I could add the code:

[code=php]
mysql_num_rows() in an if() statement to test for a result of 0.
[/code]


But I dont know how/where to add the codes

[code=php]
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'>
<p>Search for: <input type='text' name='search' size='20' maxlength='64'></p>
<p><input type='submit' value='Search'></p>
</form>

<?php
if(isset($_POST['search']))
{
$connx = mysql_connect('localhost', 'xxxxxxx', 'xxxxxxx') or die("connx");
$db = mysql_select_db('xxxxxxx') or die(mysql_error());

# convert to upper case, trim it, and replace spaces with "|":
$search = (ini_get('magic_quotes_gpc')) ? stripslashes($_POST['search']) :
$_POST['search'];
$search = mysql_real_escape_string($search);
$search = strtoupper(preg_replace('/s+/', '|', trim($_POST['search'])));

# create a MySQL REGEXP for the search:
$regexp = "REGEXP '[[:<:]]($search)[[:>:]]'";
$query = "SELECT * FROM xxxxxxx WHERE UPPER(xxxxxxx) $regexp OR ".
"xxxxxxx $regexp";
$result = mysql_query($query) or die($query . " - " . mysql_error());

echo "<table>n";
while($row = mysql_fetch_assoc($result))

{
echo "<tr>";
echo "<td><img src=../thumbs/{$row['type']}/{$row['folder']}/{$row['date']}-{$row['num']}/{$row['thumbimage']} border=1></td>";
echo "<td>{$row['name']}</td>";
echo "<td>{$row['date']}</td>";
echo "<td><a href=view.php?id={$row['id']} target=blank>View</a></td>";
echo "</tr>n";
}

}
?>
[/code]


Where do I add your codes?

Maybe you can add it for me and post it so I can see it. I really hope you will help me ?
Copy linkTweet thisAlerts:
@GertKOct 23.2013 — Any help on this?
Copy linkTweet thisAlerts:
@NogDogOct 23.2013 — Let's just take a (very) basic example, and see if you can figure out how/where to use it in your application:
[code=php]
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
// do the stuff you want to do when results are found here
}
else {
// no results were found, so handle that situation here, for example:
echo "<p>Sorry, no results matched your search.</p>";
}
[/code]
Copy linkTweet thisAlerts:
@GertKOct 23.2013 — hmmm, I have been trying all type of options (I think) but could not find the right one to use. The best one I can come up with is:

[code=php]
# create a MySQL REGEXP for the search:
$regexp = "REGEXP '[[:<:]]($search)[[:>:]]'";
$query = "SELECT * FROM galleries WHERE UPPER(keywords1) $regexp OR ".
"keywords2 $regexp";
$result = mysql_query($sql);

echo "<table>n";
if(mysql_num_rows($result) > 0)

{
echo "<tr>";
echo "<td><img src=../thumbs/{$row['type']}/{$row['folder']}/{$row['date']}-{$row['num']}/{$row['thumbimage']} border=1></td>";
echo "<td>{$row['name']}</td>";
echo "<td>{$row['date']}</td>";
echo "<td><a href=../members/viewgallery.php?id={$row['id']} target=blank>View</a></td>";
echo "</tr>n";
}

}

else {
echo "<p>Sorry, no results matched your search.</p>";
}

[/code]


But I really dont know how to do this :/ Can you please show me? ?
Copy linkTweet thisAlerts:
@GertKOct 25.2013 — Sombody that are able to help me?
Copy linkTweet thisAlerts:
@GertKOct 28.2013 — I really need a hint. Can some one please help me with this part?
Copy linkTweet thisAlerts:
@GertKOct 31.2013 — Sombody that know where I can find the answer for this?
Copy linkTweet thisAlerts:
@GertKOct 31.2013 — I found out my self. Here is the code if some one else should ever need it:
[code=php]<?php
if(isset($_POST['search']))
{
$connx = mysql_connect('localhost', 'cms_main', ',J4(tgM2X.(~') or die("connx");
$db = mysql_select_db('cms_main') or die(mysql_error());

# convert to upper case, trim it, and replace spaces with "|":
$search = (ini_get('magic_quotes_gpc')) ? stripslashes($_POST['search']) :
$_POST['search'];
$search = mysql_real_escape_string($search);
$search = strtoupper(preg_replace('/s+/', '|', trim($_POST['search'])));

# create a MySQL REGEXP for the search:
$regexp = "REGEXP '[[:<:]]($search)[[:>:]]'";
$query = "SELECT * FROM galleries WHERE UPPER(keywords57) $regexp OR ".
"keywords58 $regexp OR ".
"keywords59 $regexp OR ".
"keywords60 $regexp";
$result = mysql_query($query) or die($query . " - " . mysql_error());


echo "<table>n";
while($row = mysql_fetch_assoc($result))

{
echo "<tr>";
echo "<td><img src=../thumbs/{$row['type']}/{$row['folder']}/{$row['date']}-{$row['num']}/{$row['thumbimage']} border=1></td>";
echo "<td>{$row['name']}</td>";
echo "<td>{$row['date']}</td>";
echo "<td><a href=../members/viewgallery.php?id={$row['id']} target=blank>View Photoset</a></td>";
echo "</tr>n";
}

}
else {
echo "<p>Sorry, no results matched your search.</p>";
}
?> [/code]
×

Success!

Help @d_brandusa spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...