Web Hosting Talk







View Full Version : mySQL/PHP Search


crEA-tEch
12-16-2003, 03:33 PM
Hey guys :)

I have searched far and wide and can't find a mySQL/PHP search script that works :(

Do you know any script that is simple... just a simple search where you enter the word(s) and results come up displaying results...?

Thanks in advance

crE

Burhan
12-16-2003, 05:21 PM
This should get you started. I can't vouch for its database effectiveness (using %-type wildcards is never a good idea), but its something you can work on.


$word = "flower";
$search_column = "plant_type";
$search_table = "plants";

/* connect to your mysql database here */

$sql = "SELECT * FROM ".$search_table." WHERE ";
$sql .= $search_column." LIKE '".$word."%'";

if (!($result = mysql_query($sql)))
{
die(mysql_errno()." : ".mysql_error());
}

if (mysql_num_rows($result) == 0)
{
echo "Sorry, your search for ".$word." yielded no results";
exit;
}
echo "We found ".mysql_num_rows($result)." results<br />";

while($row = mysql_fetch_assoc($result))
{
/* Since I don't know what columns you have,
this generic loop will list each column with
its returned value. Of course in a production
version, this part would be quite detailed */

while(list($key,$val) = each($row))
{
echo $key." = ".$val."<br />";
}
}

Jakiao
12-16-2003, 07:18 PM
Here's a very simple search that you can use:

<?php

$dbconnection_var = mysql_connect("host", "user", "password");
mysql_select_db("dbname",$dbconnection_var);

if ( !$action == "search" ) {

print "

<form action=\"$PHP_SELF?action=search\" method=\"post\">
<input type=\"name\" name=\"word\"> <br>
<input type=\"submit\" value=\"Search\">
</form>

";

} else {

$query = mysql_query("SELECT * FROM tablename WHERE columnname LIKE '%$work%'",$dbconnection_var);

if ( !$query ) {

print "No matches found";

} else {

while ( $var = mysql_fetch_array($query) ) {

print "Text text " . $var['columnname'];

}

}

}

?>

That will loop the code in the while() command if any results are found for as many times as instances in each unique row. If you want it to only show a few, add to the mysql_query(), at the very end, "LIMIT numberhere" right before the ",$dbconnection_var.

Later.

Edit: I added in a form base where the user can submit the word or phrase that they are searching for. You can replace it with whatever you are currently using. Just make sure that you either change all quotations in your code to \" or single quotes such as '. That way, it wont cause errors in the PHP.