Jump to content

Search mysql


Goon

Recommended Posts

Hi

 

I've created a form which prompts a user to enter a first name or surname in free text and submit. 

Upon submission I'd like the form to search a mysql table and return results that match the users text.  I think the issue is with my sql statement.  Can anyone help me with the code to search a table based on what a user types in the first name or surname field.

 


<h2>Search</h2> 
<form name="search" method="post" action="<?=$PHP_SELF?>">
Seach for: <input type="text" name="find" /> in 
<Select NAME="field">
<Option VALUE="FirstName">First Name</option>
<Option VALUE="LastName">Last Name</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>

<? 

if ($searching =="yes") 
{ 
echo "<h2>Results</h2><p>"; 


if ($find == "") 
{ 
echo "<p>You forgot to enter a search term"; 
exit; 
} 

    include("db_config.php"); 

    $table = "customer";

    $connection = mysql_connect( DB_HOST, DB_USER, DB_PASSWORD)
        or die ("Couldn't connect to server (1)");

    $db = mysql_select_db( DB_NAME, $connection)
        or die ("Couldn't connect to database (2)");

$find = strtoupper($find); 
$find = strip_tags($find); 
$find = trim ($find); 


$data = mysql_query("SELECT * FROM users WHERE upper($field) LIKE'%$find%'"); 


while($result = mysql_fetch_array( $data )) 
{ 
echo $result['fname']; 
echo " "; 
echo $result['lname']; 
echo "<br>"; 
echo "<br>"; 
} 

 

Link to comment
https://forums.phpfreaks.com/topic/124855-search-mysql/
Share on other sites

you need a space between LIKE and the string.  for the record, you should get into the habit of adding a die() clause to your queries while testing to capture any syntax errors:

 

$data = mysql_query("SELECT * FROM users WHERE upper($field) LIKE'%$find%'");

 

should be:

 

$data = mysql_query("SELECT * FROM users WHERE upper($field) LIKE '%$find%'") or die(mysql_error()); 

Link to comment
https://forums.phpfreaks.com/topic/124855-search-mysql/#findComment-645047
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.