1+ <?php
2+ /*
3+ This function needed to create keywords from a string, which is target for search.
4+ Having keywords column in DB table makes search more efficient, because:
5+ -Saves time for processing the target string during the search.
6+ -Creates the possibility of adding new keywords by which the target string can be found without changing it.
7+ -Creates the possibility of excluding exception words (or service words).
8+
9+ !!! Before you use the code make sure that you have created 'keywords' column in target table.
10+
11+ In this example I have created keywords for the table 'cities'.
12+ */
13+ $ conn = mysqli_connect ("host " , "login " , "password " , "database " );
14+ mysqli_query ($ conn , "SET NAMES 'utf8' COLLATE 'utf8_general_ci' " );
15+ mysqli_query ($ conn , "SET CHARACTER SET 'utf8' " );
16+
17+ // This process can take for a while if you have a lot of items in the table. You can increase the time if necessary.
18+ ini_set ('max_execution_time ' , 1000 );
19+
20+ // words that do not carry a semantic load for search (use optionally)
21+ $ servWords = array ("and " , "or " , "of " , "a " , "the " , "some " , "any " );
22+ $ errors = [];
23+
24+ $ sql = "SELECT `city`, `id` FROM `cities` " ;
25+ $ res = mysqli_query ($ conn , $ sql );
26+
27+
28+ while ($ row = mysqli_fetch_assoc ($ res )) {
29+ $ textArr = [];
30+ $ keysArr = [];
31+
32+ $ id = $ row ['id ' ];
33+ $ name = preg_replace ("/[^\w\s]/iu " , "" , $ row ['city ' ]);
34+ $ textArr = preg_split ("/[\W]/iu " , mb_strtolower ($ name ), null , PREG_SPLIT_NO_EMPTY );
35+
36+ foreach ($ textArr as $ aKey => $ a ) {
37+ if (!in_array ($ a , $ servWords )) {
38+ $ keysArr [] = $ a ;
39+ }
40+ // OR (if you don't want to use exceptions)
41+ // $keysArr[] = $a;
42+ }
43+
44+ $ keys = implode ("+ " , $ keysArr );
45+ $ keys = '+ ' . $ keys ;
46+
47+ $ sql2 = "UPDATE `cities` SET `keywords`=' $ keys' WHERE `id`=' $ id' " ;
48+ $ res2 = mysqli_query ($ conn , $ sql2 );
49+
50+ if ($ res2 == false ) {
51+ $ errors [] = 'error with city ' . $ row ['city ' ] . '- ' . $ row ['id ' ];
52+ }
53+ }
54+
55+ if (empty ($ errors )) {
56+ echo '1 ' ;
57+ } else {
58+ echo json_encode ($ errors );
59+ }
60+
61+ mysqli_close ($ conn );
0 commit comments