PHP Database Search

Discussion in 'PHP' started by sonu21, Jan 29, 2012.

  1. #1
    Solved! View solution.
    sonu21, Jan 29, 2012 IP
  2. #2
    It's really simple actually.

    
    <?php
    	
    	if ( $_POST['search-bt'] ) {
    	
    		// Make the SQL Connection
    		$link = mysql_connect('localhost', 'username', 'password') or die('Could not connect: ' . mysql_error());
    				mysql_select_db('database', $link); 
    		
    		// Check there values have been set
    		if( array_key_exists ( 'search' , $_POST ) && $_POST['search'] != '' ){		
    				
    			// Temporary variables for easier handle
    			$searchTxt = $_POST['search'];     
    			 
    			// Make the Query
    			$search = mysql_query("SELECT * FROM `myTable` WHERE `myColum` LIKE %'" . $searchTxt . "'%", $link ) or die(mysql_error());
    			
    			$results = false;      
    			
    			// Check it exists
    			if ( mysql_num_rows ( $search ) != 0 ){
    				
    				$results = mysql_fetch_array ( $search ) ;
    				           
    			}
    			
    		}
    
    
    	} 
    
    
    	if ( ! $results ) {
    		// There's no results
    	} else if ( is_array ( $results ) && count ( $results ) != 0) {
    		// There's results
    	} else {
    		// Bad call or some sort of ahcking here
    	}
    
    
    ?>          
                    
    
    
    <h1>Search</h1>                      
    
    
    <form action="" method="post">              
    <label for="search">Search Text:</label>              
    <input type="text" name="search" value="" />                        
    <input type="submit" name="search-bt" value="Search" />          
    </form>  
    </body></html>
    
    Code (markup):
    Replace the connection data & query information to yours.
    WHERE X_COLUM LIKE %%

    Means it will search in that column all rows that contain a piece of that.
    Example, you search "cheese" and you rows are:
    Row1: I lik echeese
    Row2: I like ham
    Row3: Rats eat cheese

    Only Row1 and 3 would jump out.
     
    maureeeteeeee, Feb 1, 2012 IP
  3. sonu21

    sonu21 Member

    Messages:
    102
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    26
    #3
    Thanks for this code.Great!
     
    sonu21, Feb 2, 2012 IP