www.webdeveloper.com
Results 1 to 3 of 3

Thread: Search mySQL DB with any number of optional terms

  1. #1
    Join Date
    Jan 2012
    Posts
    12

    Search mySQL DB with any number of optional terms

    First time writing this type of script. I thought I'd share it and see if anyone has suggestions for improvement (it works). Hopefully the comments are clear enough. Thanks!

    PHP Code:
    <?php if ( isset($_POST['submit']) ) {                    

            
    $rec_number 1;
            
    $count 0;
            
    $query "SELECT * FROM properties WHERE ";         //the sql query will be build on this
            
    unset($_POST['submit']);                            //detele this key because it throws off the calculations
            
            
    foreach ( $_POST as $key => $value ) {                //the keys of this varible must match the equivalent db columns to be searched

                
    if ( $value != "" ) {                           //Do this with every search item that has a value

                    
    $count=$count+1;

                    if ( 
    $count == ) {                         //one term search does not require AND and must be handled separately
                        
    $query $query "$key='$value'"
                        }
                    else {                                       
    //Multiple terms require the AND in between terms and builds on the one term search
                        
    $query $query " AND $key='$value'";
                    }
                    
                    }    
        
                }

            
    //run query
            
    if ( $count == ) {                                   //if there are no search terms, say so
                
    echo "There are no search terms!"
                } ELSE {                                           
    //run it
                
                //optionally, add and ORDER BY option here to reorder the results, 
                //or even include that option in the search form and then append it to the query here
                //but it will complicate the counting routine

                
    $query $query.";";
                
    $result mysql_query($query);
                include 
    'display_results.php';

                } 
    ?>

  2. #2
    Join Date
    Feb 2012
    Posts
    218
    The perfect environment for SQL injection...

  3. #3
    Join Date
    Jan 2012
    Posts
    12
    Thanks for that reminder... I'm going to control that with user sql user privileges.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles