php search

Discussion in 'PHP' started by kingerrormessage, Nov 25, 2007.

  1. #1
    i have started a search function for my website, which so far simply posts the users search words to the results page, but i don't know what function i need to check these words against the data in my mysql database.

    i don't want the user to be limited to 1 word in the search box, and i don't want to search for exact matches, just search for which mysql entries has the words they are looking for.

    any help would be greatly apreciated.

    on a similar note, does anyone know of a site which can explain to me about how to make the searchbox (and other forms on my site) more secure against unwanted spam/code injection.

    thanks


    edit: i've got the search working now, but validation help would be much apreciated
     
    kingerrormessage, Nov 25, 2007 IP
  2. bobb1589

    bobb1589 Peon

    Messages:
    289
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #2
    
    <?php
    
    $search = explode(" ",$_POST['search']);
    
    foreach($search as $word){
    $word = trim($word);
    $sql = mysql_query("SELECT * FROM tablename WHERE fieldname LIKE '%$word%'");
    $r = mysql_fetch_assoc($sql);
    
    ?>
    
    PHP:
    that should be usable, it is pretty simple and wouldn't be as accurate as other ways, but it should still work

    sorry, didn't realize you edited your post
     
    bobb1589, Nov 25, 2007 IP
  3. -NB-

    -NB- Peon

    Messages:
    153
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Here's a nifty little function I wrote to clean arrays and strings, will help you out with the SQL Injection problems, etc.

    
    function clean ($string) {
    	if (is_array($string)) {
    		foreach ($string as $key => $value) {
    			if (function_exists('mysql_real_escape_string')) {
    				$string[$key] = mysql_real_escape_string($value);
    			} else {
    				$string[$key] = addslashes($value);
    			}
    		}
    	} elseif (is_string($string)) {
    		if (function_exists('mysql_real_escape_string')) {
    			$string = mysql_real_escape_string($string);
    		} else {
    			$string = addslashes($string);
    		}
    	}
    	return $string;
    }
    
    PHP:
     
    -NB-, Nov 26, 2007 IP
  4. kingerrormessage

    kingerrormessage Guest

    Messages:
    19
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    sorry if this is a stupid question, but can you explain how i would perform this function on the variable from my searchbox which is $search.

    thank you
     
    kingerrormessage, Nov 27, 2007 IP
  5. bobb1589

    bobb1589 Peon

    Messages:
    289
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #5
    just like you would any function, just pass the required value

    $cleanstring = clean($search);
     
    bobb1589, Nov 27, 2007 IP