../www/get_script_html_files/strip/search.py
1 #!/usr/bin/python2
2
3 #######################################
4 #
5 # This script is used to search DB and generate page with regults
6 #
7 # Version: 1.5
8 #
9 #######################################
10
11 #import all functions from lib.py
12
13 from lib import *
14
15 form = cgi.FieldStorage()
16
17 try:
18 keyword = form['keyword'].value
19 except:
20 keyword = ''
21
22 #function to search column title of table books
23
24 def do_search(keyword):
25
26 sql = "SELECT id FROM books WHERE MATCH (title) AGAINST ('%s' IN BOOLEAN MODE)" % keyword.lower()
27
28 #### BUG #1
29 #### Expected: programmer should've used function select() to select all matching rows
30 #### Actual: function select_one() was used instead, so only first matching record will be returned
31 #### Note 1:
32 #### see description for both functions in code of lib.py
33 #### Note 2:
34 #### As an example: in table 'books' we have two records containing keyword 'adventures':
35 #### "the adventures of tom sawyer" (id=3) and 'the adventures of huckleberry finn' (id=10)
36 #### So, when user enters 'adventures', only record with id=3 will be returned.
37 #### Why? Because: 1. select_one() gets first record it sees. 2. that first record will be record with id=3 (3<10)
38
39 tmp_list = select_one(sql)
40
41 #if nothing is returned by search
42
43 if len(tmp_list) == 0:
44
45 return ''
46
47 else:
48
49 #go over returned list and generate html
50
51 #### Note:
52 #### the rest of the code for this function was written as if select() was used and, hence, several records can be returned
53
54 table="<table>"
55
56 for item in tmp_list:
57
58 table = table + show_book(item)
59
60
61 table=table + "</table>"
62
63 return table
64
65
66 ############Main logic
67
68 #if no keyword is provided
69
70 if keyword == '':
71
72 body_html = ''
73 message = "Oops, error. No keyword is provided"
74
75 #it's unfortunate but MySQL search engine has default limitation of seaching for words with 4 or more chars only
76 #we cannot change this now, so we created a message for our users
77
78 elif len(keyword) <= 3:
79
80 body_html = ''
81 message = "Please, note that current MySQL settings don't allow searches for words containing less than 4 chars"
82
83 else:
84
85 body_html = do_search(keyword)
86
87 if body_html == '':
88
89 message = "Nothing is found :("
90
91 else:
92
93 message = ''
94
95 #execute code below if this script is run as standalone script
96 #don't execute code below if we import functions from this script
97
98 if __name__ == "__main__":
99
100 ############Determine if user is logged in
101
102 is_logged_in = is_logged_in()
103
104 #############generate and print html
105
106 print 'Content-Type: text/html\n\n'
107
108 caption = 'Search'
109
110 html=get_html(is_logged_in,body_html,caption,message)
111
112 print html
113