PHP - Parameterized Fulltext Proximity Search
I have a MySql database (Server Version 5.6.12) with a fulltext index on the SectionText field in the FD table with this structu
CREATE TABLE `FD` ( `FTS_DOC_ID` bigint(20) unsigned NOT NULL, `ReadingNo` int(11) DEFAULT NULL, `SequenceNo` int(11) DEFAULT NULL, `SectionTypeID` int(11) DEFAULT NULL, `SectionText` longtext, `FullDocNo` varchar(11) CHARACTER SET utf8 NOT NULL, `DocType` varchar(11) CHARACTER SET utf8 DEFAULT NULL, UNIQUE KEY `FTS_DOC_ID_INDEX` (`FTS_DOC_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;I am able to do a very accurate fulltext proximity search (92 documents found) in PHPMyAdmin using this syntax: SELECT SectionText FROM fd WHERE DocType = "text" AND MATCH (SectionText) AGAINST ('"liver hepatic" @3' IN BOOLEAN MODE) ORDER BY FTS_DOC_IDBut when I try to use this query on a webpage I get this error message: Parse error: syntax error, unexpected 'liver' (T_STRING) in C:\wamp\www\ecr\proximity.php on line 77 When I remove the quotes like this: MATCH (SectionText) AGAINST ('liver hepatic @3' IN BOOLEAN MODE)There is no error, but there are no documents found. Realistically, to do searches on the web, I need to use search variables provided via an input form (and preferably a parameterized query) such as: MATCH (SectionText) AGAINST (':search1 :search2 @:proximity' IN BOOLEAN MODE)But this also returns no documents found. I need help getting this implemented on a web page. If this needs to be posted in another forum (PHP), please advise. But since the proximity search feature seems to be relatively new and somewhat obscure (couldn’t find anything about implementing it on a webpage via Google), I thought it best to start here. Any help in solving this is greatly appreciated. Similar TutorialsHello everybody! I have a fulltext search script that orders the results by relevance to the keywords. But I want that the order process takes into consideration column `views` as well. So basically what I want is that relevance is 80% significant but views respectively - 20%. I tried to figure out some ways, but as I am amateur there were only errors that came out. Here ismMy code which is working and ordering the results ONLY 100% by revelance: Code: [Select] $mq = mysql_query("SELECT *, (MATCH(articles) AGAINST ('briniskigi housez lacitis' IN BOOLEAN MODE)) AS relevance FROM results WHERE ( MATCH(articles) AGAINST ('briniskigi housez lacitis' IN BOOLEAN MODE) ) ORDER BY relevance DESC"); while($row = mysql_fetch_array($mq)) { echo $row['id'] . '<br />'; } Thank you in advance. I hope that you understood me The issue I am having is that everytime I click the next button, it takes me to the index page. My question is, how do I set up a proper search results link in "href="?page=1"
index.php
<form action="search" method="GET"> <input type="search" name="search" placeholder="Find products, services ..."> <input type="submit" name="submit" value=""> </form>search.php if(isset($_GET['submit']) && !empty($_GET['search'])) { $value = escape(trim(Input::get('search'))); try { // Find out how many items are in the table $q = DB::getInstance()->query("SELECT * FROM records WHERE MATCH(title) AGAINST('$value' IN BOOLEAN MODE)"); $total = $q->count(); // How many items to list per page $limit = 10; // How many pages will there be $pages = ceil($total / $limit); // What page are we currently on? $page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array( 'options' => array( 'default' => 1, 'min_range' => 1, ), ))); // Calculate the offset for the query $offset = ($page - 1) * $limit; // Some information to display to the user $start = $offset + 1; $end = min(($offset + $limit), $total); // Prepare the paged query $stmt = DB::getInstance()->query("SELECT users.*, records.* FROM records LEFT JOIN users ON records.user_id = users.user_id WHERE MATCH(title) AGAINST('$value' IN BOOLEAN MODE) ORDER BY relevance DESC LIMIT {$limit} OFFSET ".$offset); if($stmt->count()) { // Display the results foreach($stmt->results() as $row) { $date = escape($row->posted); $record_date = escape(Input::facebook_date_format($date)); $record_id = escape($row->record_id); $title = trim($row->title); $slug_title = $row->slug_title; $view_count = escape(intval(number_format($row->views + 1))); $username = escape($row->username); require 'snippets/record_widget.php'; } } else { ?><div class="message"><?php echo 'No records found.';?></div><?php } <?php // The "back" link $prevlink = ($page > 1) ? '<a href="?page=1" title="First page"><img src="images/left-page-arrow-end.png"/></a> <a href="?page=' . ($page - 1) . '" title="Previous page"><img src="images/left-page-arrow-start.png"/></a>' : '<span class="disabled"><img src="images/left-page-arrow-end-disabled.png"/></span> <span class="disabled"><img src="images/left-page-arrow-start-disabled.png"/></span>'; // The "forward" link $nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page"><img src="images/right-page-arrow-start.png"/></a> <a href="?page=' . $pages . '" title="Last page"><img src="images/right-page-arrow-end.png"/></a>' : '<span class="disabled"><img src="images/right-page-arrow-start-disabled.png"/></span> <span class="disabled"><img src="images/right-page-arrow-end-disabled.png"/></a></span>'; // Display the paging information ?> <div class="pages"> <span class="pages-arrows"><?php echo $prevlink; ?></span> <span class="pages-numbers"><?php echo $page; ?> of <?php echo $pages; ?></span> <span class="pages-arrows"><?php echo $nextlink; ?></span> </div> } catch (Exception $e) { echo '<p>', $e->getMessage(), '</p>'; } } else { Redirect::to('index'); } Edited by man5, 20 August 2014 - 10:27 PM. In phpmyadmin, once I do a fulltext on a field, is that the only time I have to do it or does it have to be indexed anytime new data is added or altered? Hi guys, i'm trying to search from a form and use php to display the results of the FullText Search from a MySQL database, but I don't get any results from the query. This is the query: $query="SELECT * FROM tutorials WHERE MATCH(title, tags) AGAINST ('$searchform')"; I think the query is right but it doesn't give me any results.... Does anyone know what could be wrong? I think it might be something wrong with my table (database). my table should have 5 columns: id, title, category, content, tags The form should search throught the title and tags columns to see if it finds anything matching the $searchform , but I don't think it is doing it. Can anyone help please? Hello everyone. First post here. very new to php and html. Im working on my uncles website which is a fabric store. I created a mysql database and a search to use. Im trying to make this a fulltext search because right now you have to match the pattern name exactly to get any results! And if somebody searches for the pattern name and the color they will get no results! In fact, if there is more than one search term, there is no results. -This is the first part where it counts so the pagination can be built- $sql = "SELECT COUNT(*) FROM rapatterns WHERE Pattern= '$keyword' OR Color= '$keyword' OR Fabric_Use= '$keyword'"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); -here is the query to get results- $sql = "SELECT * FROM rapatterns WHERE Pattern= '$keyword' OR Color= '$keyword' OR Fabric_Use= '$keyword' LIMIT $offset, $rowsperpage"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); Ive looked into full text searching, and ive created a fulltext index on the three columns being searched here. The problem im having is when I try to change the queries to fulltext searches I get syntax errors. -this is what i was trying to do- -this is the first one that counts for pagination- $sql = "SELECT COUNT(*) FROM rapatterns WHERE MATCH(Pattern,Color,Fabric_Use) AGAINST ('$keyword') LIMIT $offset, $rowsperpage"; -here is the second one to get results- $sql = "SELECT * FROM rapatterns WHERE MATCH(Pattern,Color,Fabric_Use) AGAINST ('$keyword') LIMIT $offset, $rowsperpage"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); Im wondering if I can get a little help with the syntax or if what im trying to do wont work at all. Go easy on me. I am extremely new to any of this. fulltext in boolean mode is not matching ignored words in mysql.
ENGINE is set for myisam. mysql collation is utf8_general_ci.
i have altered table using...
ALTER TABLE users ADD FULLTEXT(userName);when i view mysql indexes, userName is username instead. I am not sure if this matter as there is not an error message when searching. SELECT * FROM users WHERE MATCH (userName) AGAINST ('$keywords' IN BOOLEAN MODE)I have restarted mysql and still does not match some 5 character words. in the mysql config, word length is set to 4. have i missed something? The result pages is supposed to have pagination like google help me please
I require a page to be added to my website. This page will facilitate a refined search via Google, Bing and Yahoo search engine simultaneously , show the top 5 of each engine. Is this possible using php ? Thank's Hello, Does anyone know a tutorial I can follow to create my own search engine over the items I have in my SQL database? I find a lot of tutorials but they are all 'one word searches' which means if you type two words you will get all results that contain either word (too many hits). If the search engine tutorial displays result with AJAX even better. Thanks for help. df Hi all How do I modify the below code to search multiple tables in mySQL database? $query = "select * from store_items where description like \"%$trimmed%\" or title like \"%$trimmed%\" or dimensions like \"%$trimmed%\" order by id ASC"; $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); It is for a search function and I need it to search another table called 'about_text' and 'faq_text' Thanks Pete Hello, I'm developing a website that asks the user to submit a keyword for a search. The results should display matches for this keyword, but also show matches for related keywords (in order of relevenace!). I'm planning on building up a library of which search terms users use in the same sessions (e.g. if someone searches for "it jobs" and "php jobs", I'll know the terms are correlated), and I'll also measure the click-through rates of the items on the results list. I've been spending all weekend trying to map out the design for this but it's proving incredibly complicated and I think the solution is likely to be on the internet somewhere already?! Please could someone point me in the right direction if you've come accross this problem before? Thanks a million, Stu Hello. I am working on a php script for searching a database table. I am really new to this, so I used the this tutorial http://www.phpfreaks.com/tutorial/simple-sql-search I managed to get all the things working the way I wanted, except one important and crucial thing. Let me explain. My table consist of three columns, like this: ID(bigint20) title(text) link (varchar255) ============================= ID1 title1 link-1 ID2 title2 link-2 etc... Like I said, I managed to make the script display results for a search query based on the title. Want I want it to do more, but I can't seem to find the right resource to learn how, is to place a "Download" button under each search result with its corresponding link from the table. Here is the code I used. <?php $dbHost = 'localhost'; // localhost will be used in most cases // set these to your mysql database username and password. $dbUser = 'user'; $dbPass = 'pass'; $dbDatabase = 'db'; // the database you put the table into. $con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error()); mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error()); // Set up our error check and result check array $error = array(); $results = array(); // First check if a form was submitted. // Since this is a search we will use $_GET if (isset($_GET['search'])) { $searchTerms = trim($_GET['search']); $searchTerms = strip_tags($searchTerms); // remove any html/javascript. if (strlen($searchTerms) < 3) { $error[] = "Search terms must be longer than 3 characters."; }else { $searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection. } // If there are no errors, lets get the search going. if (count($error) < 1) { $searchSQL = "SELECT title, link FROM db WHERE title LIKE '%{$searchTermDB}%'"; $searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}"); if (mysql_num_rows($searchResult) < 1) { $error[] = "The search term provided {$searchTerms} yielded no results."; }else { $results = array(); // the result array $i = 1; while ($row = mysql_fetch_assoc($searchResult)) { $results[] = "{$row['title']}<br /> Download - this is the button I want to link to the title results - and maybe other links too - <br /> "; $i++; } } } } function removeEmpty($var) { return (!empty($var)); } ?> <?php echo (count($error) > 0)?"The following had errors:<br /><span id=\"error\">" . implode("<br />", $error) . "</span><br /><br />":""; ?> <form method="GET" action="search?" name="searchForm"> Search for title: <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /> <input type="submit" name="submit" value="Search" /> </form> <?php echo (count($results) > 0)?"Rezultate lucrari de licenta sau disertatie pentru {$searchTerms} :<br /><br />" . implode("", $results):""; ?> $results = array(); // the result array $i = 1; while ($row = mysql_fetch_assoc($searchResult)) { $results[] = "{$row['title']}<br /> Download - this is the button I want to link to the title results - and maybe other links too - <br /> "; $i++; I would like the results to be displayed like this Results for SearchItem: Result 1 Download | Other link Result 2 Download | Other link etc.... or something like this. So, how do I add the data from the link row into a text(Dowload), within an <a href> tag (well, at least I guess it would go this way) ? My first tries (fueled by my lack of knowledge) where things like $results[] = "{$row['title']}<br /> <a href="{$row['link']}">Download</a> <br /> "; but I keep getting lots of errors, and then I don't know much about arrays and stuff (except basic notions); So there it is. I am really stuck and can't seem to find any workaround for this. Any suggestions? (examples, documentation, anything would do, really) Thanks, Radu I am developing a intranet forum in Php and MySQL and I am using ajax to display searched results on the same page but right now I am using query LIKE text% to search in database which is slower. but I want to make it fast search engin which can parse *,+ and show result. Since I am using ajax i am not able to use free search engin,so if possible pls provide a complete solution I have code to search a database of members, I can search by lastname but having a little problem. I want to be able to search by lastname starting with the first letter. (ie: a or b or c or d and so on). As it is right now I can only search by first letter of last name if I add % to the search (ie: a% b% c%) will give me all members with the last names starting with the approiate letter designation. I'm not sure how to handle this, any help would be appreciated. Thanks. Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <center><table cellspacing="10" cellpadding="10" width="750" border="0"> <h4>Search</h4> <form name="search" method="post" action="<?php $PHP_SELF?>"> Seach for: <input type="text" name="find" /> in <Select NAME="field"> <Option VALUE="lname">Last Name</option> <input type="hidden" name="searching" value="yes" /> <input type="submit" name="search" value="Search" /> </form> <?php // check to see if anything is posted if (isset($_POST['find'])) {$find = $_POST['find'];} if (isset($_POST['searching'])) {$searching = $_POST['searching'];} if (isset($_POST['field'])) {$field = $_POST['field'];} //This is only displayed if they have submitted the form if (isset($searching) && $searching=="yes") { echo "<h4>Results</h4><p>"; // If they did not enter a search term we give them an error if (empty($find)) { echo "<p>You forgot to enter a search term"; exit; } // Otherwise we connect to our Database mysql_connect("localhost", "root", "1910") or die(mysql_error()); mysql_select_db("cmc_member") or die(mysql_error()); // We preform a bit of filtering $find = strtoupper($find); $find = strip_tags($find); $find = trim ($find); // Now we search for our search term, in the field the user specified $results = mysql_query("SELECT * FROM members WHERE upper($field) LIKE'$find'"); // And we display the results if($results && mysql_num_rows($results) > 0) { $i = 0; $max_columns = 3; while($row = mysql_fetch_array($results)) { // make the variables easy to deal with extract($row); // open row if counter is zero if($i == 0) echo "<tr>"; // make sure we have a valid product ALIGN='CENTER' if($fname != "" && $fname != null) echo "<td ALIGN='CENTER'><FONT COLOR='red'><b>$fname $lname</b></FONT><br> $address <br> $city $state $zip <br>$phone<br><a href=\"mailto: $email\">$email</a><br></td>"; // increment counter - if counter = max columns, reset counter and close row if(++$i == $max_columns) { echo "</tr>"; $i=0; } // end if } // end while } // end if results // clean up table - makes your code valid! if($i < $max_columns) { for($j=$i; $j<$max_columns;$j++) echo "<td> </td>"; } //This counts the number or results - and if there wasn't any it gives them a little message explaining that $anymatches = mysql_num_rows($results); if ($anymatches == 0) { echo "Sorry, but we can not find an entry to match your query<br><br>"; } //And we remind them what they searched for echo "<b>Searched For:</b> " .$find; } ?> </tr> </table></center> </body> </html> Friends, I want to extract the Search Keyword from the URL, a visitor came from. I am using a PHP CMS and want to show the Keyword on my Blog. So if they search "abcd" from google, i want to extract "abcd" and echo on my blog. Here is the coding i could got hold of, but its not working, not echoing anything <?php function pk_stt2_function_get_delimiter($ref) { $search_engines = array('google.com' => 'q', 'go.google.com' => 'q', 'images.google.com' => 'q', 'video.google.com' => 'q', 'news.google.com' => 'q', 'blogsearch.google.com' => 'q', 'maps.google.com' => 'q', 'local.google.com' => 'q', 'search.yahoo.com' => 'p', 'search.msn.com' => 'q', 'bing.com' => 'q', 'msxml.excite.com' => 'qkw', 'search.lycos.com' => 'query', 'alltheweb.com' => 'q', 'search.aol.com' => 'query', 'search.iwon.com' => 'searchfor', 'ask.com' => 'q', 'ask.co.uk' => 'ask', 'search.cometsystems.com' => 'qry', 'hotbot.com' => 'query', 'overture.com' => 'Keywords', 'metacrawler.com' => 'qkw', 'search.netscape.com' => 'query', 'looksmart.com' => 'key', 'dpxml.webcrawler.com' => 'qkw', 'search.earthlink.net' => 'q', 'search.viewpoint.com' => 'k', 'mamma.com' => 'query'); $delim = false; if (isset($search_engines[$ref])) { $delim = $search_engines[$ref]; } else { if (strpos('ref:'.$ref,'google')) $delim = "q"; elseif (strpos('ref:'.$ref,'search.atomz.')) $delim = "sp-q"; elseif (strpos('ref:'.$ref,'search.msn.')) $delim = "q"; elseif (strpos('ref:'.$ref,'search.yahoo.')) $delim = "p"; elseif (preg_match('/home\.bellsouth\.net\/s\/s\.dll/i', $ref)) $delim = "bellsouth"; } return $delim; } /** * retrieve the search terms from search engine query * */ function pk_stt2_function_get_terms($d) { $terms = null; $query_array = array(); $query_terms = null; $query = explode($d.'=', $_SERVER['HTTP_REFERER']); $query = explode('&', $query[1]); $query = urldecode($query[0]); $query = str_replace("'", '', $query); $query = str_replace('"', '', $query); $query_array = preg_split('/[\s,\+\.]+/',$query); $query_terms = implode(' ', $query_array); $terms = htmlspecialchars(urldecode(trim($query_terms))); return $terms; } /** * get the referer * */ function pk_stt2_function_get_referer() { if (!isset($_SERVER['HTTP_REFERER']) || ($_SERVER['HTTP_REFERER'] == '')) return false; $referer_info = parse_url($_SERVER['HTTP_REFERER']); $referer = $referer_info['host']; if(substr($referer, 0, 4) == 'www.') $referer = substr($referer, 4); return $referer; } $referer = pk_stt2_function_get_referer(); if (!$referer) return false; $delimiter = pk_stt2_function_get_delimiter($referer); if( $delimiter ){ $term = pk_stt2_function_get_terms($delimiter); } echo $term; ?> May someone help? Natasha T Hello All, Need some help I have 2 tables in a database and I need to search the first table and use the results from that search, to search another table, can this be done? and if it can how would you recommend that I go about it? Thanks For Your Help Guys! I want to know how to display results from mysql database by filling in a form. but i have found a tutorial which shows typing in a text box which displays results. if i follow this tutorial will it help me to understand and create php coding to display results for my form? Hi, any one have any idea of how the search box work? when you type in some words, it will automatically drop down a list related to the words you wrote. eg. http://www.yellowpages.co.za/# http://www.yell.com/ i would like to know they used what to do the search engine. and if there is any site that have the demo. thanks. Hi there, I'm working on a search bar for my website and I want what ever someone types in, to be like the data in my table column name. My table column name is 'make', my table name is 'stick'. At the moment, my code outputs " your search: "..mysearchterm.." returned zero results", even when i type in the same name as a row in my column. Can anyone make sense of why my code's not performing? Code: [Select] <form id="search" name="search" id="search" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>" /> <input type="text" name="terms" value="Search..." /> <input class="button" type="submit" name="Search" value="Search" /> </form> <?php include_once('connectvars.php'); if (isset($_GET['terms']) && ($_GET['terms'] != 'Search...') ) { $terms = $_GET['terms']; $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die *('Error connecting to MySQL server'); // Query the database. $query = "SELECT sid, type, colour, make FROM stick WHERE make LIKE '%$terms% '"; // Fetch the results. $result=mysqli_query($dbc,$query); // Print the results: $num_rows = mysqli_num_rows($result); // If the results of the query match to 1 or more rows, display the products by their title, price and image. if ($num_rows > 0){ if($result=mysqli_query($dbc,$query)){ $output = Array(); while($row=mysqli_fetch_assoc($result)) { //'<br /> Street: ' .$row['street'].' $output[] = '<ul>'; $output[] = '<li> Type: '.$row['make'] .' Size: '.$row['type'].'<br />Colour: '.$row['colour'] . '" /></li>'; $output[] = '</ul>'; } } echo join('',$output); } // If the results don't match the titles of the table, output this message. else { echo "<h3>Sorry,</h3>"; echo "<p>your search: "" .$terms. "" returned zero results</p>"; } } else { // Tell them to use the search form. echo '<p class="error">Please use the search form at the top of the window to search this site.</p>'; } ?> Thanks. |