PHP - Search Mysql With Several Words In Once?
Hi,
I am currently using this code as part of my search module: Code: [Select] $sql_res = mysql_query("SELECT * from test_user_data WHERE streng like '%$q%' or beskrivelse like '%$q%' or sku like '%$q%' ORDER BY streng LIMIT 5"); Simple code that works if my client searches for a string (or part of) that is contained in test_user_data table. If he searches "Dell Inspiron 6000", he will get a hit. However, if he searches for "Inspiron Dell 6000", he will not. Is it a simple way to make the client/enduser search for multiple words contained in a single cell? Thank you! This forum is awesome! Similar TutorialsI'm trying to pull in data using a particular word from a mysql db (it's like a search facility). But this code only picks if the db has got the exact same word. E.g. if fincom = "DALLS" it pulls the data only when "searchwords" has DALLS. It ignores if "searchwords" has BARBIE DALLS. How can I fix this. I need to pick all records which contains the search word 'fincom' anywhere in searchwords. Hope this makes scene. $SomeVar = $_POST['fincom']; $query = "SELECT * FROM news_home WHERE searchwords = '".$SomeVar."' ORDER BY timestamp DESC"; $results = mysql_query($query); Hello, i need some help/info about searching words in files (txt or xml) and saving them to db or another file.
For example ive got an xml file like below:
<families>
<family>
<name>brown</name>
<city>denver</city>
<members>12</members>
</family>
<family>
<name>jackson</name>
<city>new york</city>
<members>6</members>
</family>
</families>
i want to search for: <family> then save the lines till it comes to the word </family> and then goes to the next group. did some reading about array, preg_match, strpos functions but dont know where to start. what is the best way to do this?
can you guys give me some advise... or links to good tutorials?
thanks in advance!
Hello, I am EXTREMELY new to PHP, and coding in general. I have attempted to search for an answer to this already, but I'm not sure I'm using terminology that will lead me to an solution, as I haven't come up with much. I'm hoping that someone can provide some assistance, or at least point me in the right direction for some reading. What I am trying to do it search a string for a match to any of 12 words. I'm wondering if there is a smarter way to do this than coding 12 different lines, each one looking for a specific word. If you can point me in the right direction, then thank you very much =) I am building online dictionary with php. The following code allows the user to search a word and display the definition results from the database. The problem is the user has to input the identical words only. If the words are not exactly similar to the database words it returns error message. But in this case I need it to give a suggestion along with the error message based on the few beginning words of the submitted word. eg. if the user type a word "suggestion", and the word "suggestion" is not available in the database .... instead of just the error message to also search and include other stored data closer to the submitted word ... like "TRY the word SUGGEST". can any one help me on this please. Thank you in advance. here is the code Code: [Select] <?php $script = $_SERVER['PHP_SELF']; if(isset($_POST['sbm']) && isset($_POST['word']) ) { submited(); } else { show_form(); } function show_form() { ?> <p><center> Type <span style='font-weight:bold;'>ENGLISH</span> word Only! <span style='font-weight:bold;'>SPELL IT CORRECTLY!!!.</span></center></P> <p><center>Search</center></p> <center><form name=frm method=POST action="<?php echo $script ?>"> <p><input type=text name="word"><br /></p> <p><input type=submit name="sbm" value="Submit"> </form> </center></p> <?php } function submited() { require("dbconn.inc"); $word=$_POST['word']; $sql="select * from words where eng like '".mysql_real_escape_string($word)."'"; $result=mysql_query($sql,$link); // I assume $link is defined in dbconn.inc if(@mysql_num_rows($result)!=0) { $rows=mysql_fetch_array($result); $am=$rows["am"]; echo("<center>The Word <h1><b>$word</b></h1> in Am is : <h1><b>$am </b></h1><br></center>"); } else { echo("<center><span style='font-weight:bold;color:#FF0000;'>Could not find it! Check the spelling and try again !!</span></center>"); } // The connection will close automatically since // this is near the end of the script. mysql_close($link); show_form(); } ?> 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! Hi I have a column in my database showing Banned words. What im trying to do is to recall the list of bad words from my database and if some of them is going to be displayed they should replace it with :-x well I made the `$bwords` to recall the info from the database. Hi, Currently on my website I have a section where you can select an article held within a database, I still want this to happen but I wouldn't a different word to be linked to the article. Currently it reads 'Click here to view this entry' underneath the title of the article, I want he title of all the different articles to link to the right article is there anyway to do this? My code currently reads: Code: [Select] <?php $blog_postnumber = 5; if(!isset($_GET['page'])) { $page = 1; } else { $page = (int)$_GET['page']; } $from = (($page * $blog_postnumber) - $blog_postnumber); $sql = "SELECT * FROM cms_article ORDER BY timestamp DESC LIMIT $from, $blog_postnumber"; $result = mysql_query($sql) or print ("Can't select entries from table cms_article.<br />" . $sql . "<br />" . mysql_error()); while($row = mysql_fetch_array($result)) { $date = date("l F d Y", $row['timestamp']); $title = stripslashes($row['title']); $entry = stripslashes($row['entry']); $id = $row['id']; if (strlen($entry) > 0) { $entry = substr($entry, 0, 0); $entry = "$entry<a href=\"journal.php?id=" . $id . "\">Click here to view this entry.</a>"; } ?> The result pages is supposed to have pagination like google help me please
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 does anyone have a code todo this? a snippet or soemthing ive tried a few diffrent ones ive seen but nothing that works.. it takes whats submited in search, then takes the words, breaks them up and creates a query string with all the diffrent feilds... here is what phpadmin produces when i search SELECT * FROM `breedclads`.`activeamahorse` WHERE (`id_entered` LIKE '%green%' OR `uuid` LIKE '%green%' OR `ama_hr_coat` LIKE '%green%' OR `breedable` LIKE '%green%' OR `ama_hr_sex` LIKE '%green%' OR `ama_hr_age` LIKE '%green%' OR `date_entered` LIKE '%green%' OR `ama_hr_eyes` LIKE '%green%' OR `ama_hr_eyes_type` LIKE '%green%' OR `ama_hr_mane` LIKE '%green%' OR `ama_hr_tail` LIKE '%green%' OR `ama_hr_luster_coat` LIKE '%green%' OR `ama_hr_luster_hair` LIKE '%green%' OR `ama_hr_gleam_coat` LIKE '%green%' OR `ama_hr_gleam_hair` LIKE '%green%' OR `ama_hr_parents` LIKE '%green%' OR `ama_hr_sale_type` LIKE '%green%' OR `ama_hr_sale_price` LIKE '%green%' OR `ama_hr_location` LIKE '%green%' OR `auction_date` LIKE '%green%' OR `picture_type` LIKE '%green%' OR `picture_name` LIKE '%green%' OR `picture_size` LIKE '%green%' OR `picture_content` LIKE '%green%' OR `ama_hr_coat_type` LIKE '%green%' OR `ama_hr_coat_gloom` LIKE '%green%' OR `ama_hr_hair_gloom` LIKE '%green%' OR `ama_hr_slurl` LIKE '%green%' OR `class_link_key` LIKE '%green%') AND (`id_entered` LIKE '%albino%' OR `uuid` LIKE '%albino%' OR `ama_hr_coat` LIKE '%albino%' OR `breedable` LIKE '%albino%' OR `ama_hr_sex` LIKE '%albino%' OR `ama_hr_age` LIKE '%albino%' OR `date_entered` LIKE '%albino%' OR `ama_hr_eyes` LIKE '%albino%' OR `ama_hr_eyes_type` LIKE '%albino%' OR `ama_hr_mane` LIKE '%albino%' OR `ama_hr_tail` LIKE '%albino%' OR `ama_hr_luster_coat` LIKE '%albino%' OR `ama_hr_luster_hair` LIKE '%albino%' OR `ama_hr_gleam_coat` LIKE '%albino%' OR `ama_hr_gleam_hair` LIKE '%albino%' OR `ama_hr_parents` LIKE '%albino%' OR `ama_hr_sale_type` LIKE '%albino%' OR `ama_hr_sale_price` LIKE '%albino%' OR `ama_hr_location` LIKE '%albino%' OR `auction_date` LIKE '%albino%' OR `picture_type` LIKE '%albino%' OR `picture_name` LIKE '%albino%' OR `picture_size` LIKE '%albino%' OR `picture_content` LIKE '%albino%' OR `ama_hr_coat_type` LIKE '%albino%' OR `ama_hr_coat_gloom` LIKE '%albino%' OR `ama_hr_hair_gloom` LIKE '%albino%' OR `ama_hr_slurl` LIKE '%albino%' OR `class_link_key` LIKE '%albino%') AND (`id_entered` LIKE '%69%' OR `uuid` LIKE '%69%' OR `ama_hr_coat` LIKE '%69%' OR `breedable` LIKE '%69%' OR `ama_hr_sex` LIKE '%69%' OR `ama_hr_age` LIKE '%69%' OR `date_entered` LIKE '%69%' OR `ama_hr_eyes` LIKE '%69%' OR `ama_hr_eyes_type` LIKE '%69%' OR `ama_hr_mane` LIKE '%69%' OR `ama_hr_tail` LIKE '%69%' OR `ama_hr_luster_coat` LIKE '%69%' OR `ama_hr_luster_hair` LIKE '%69%' OR `ama_hr_gleam_coat` LIKE '%69%' OR `ama_hr_gleam_hair` LIKE '%69%' OR `ama_hr_parents` LIKE '%69%' OR `ama_hr_sale_type` LIKE '%69%' OR `ama_hr_sale_price` LIKE '%69%' OR `ama_hr_location` LIKE '%69%' OR `auction_date` LIKE '%69%' OR `picture_type` LIKE '%69%' OR `picture_name` LIKE '%69%' OR `picture_size` LIKE '%69%' OR `picture_content` LIKE '%69%' OR `ama_hr_coat_type` LIKE '%69%' OR `ama_hr_coat_gloom` LIKE '%69%' OR `ama_hr_hair_gloom` LIKE '%69%' OR `ama_hr_slurl` LIKE '%69%' OR `class_link_key` LIKE '%69%') i need this to be made when people search with mutliple words as you can see it searchs each feilds for the green then each feild for albino, so on.. but i wont ever know what there searching for Please help me, thanks Hello, I'm working on a site search which I've never done from scratch before and I've run into a couple road blocks along the way. The first problem is that in my search form it seems that there is no minimum amount of characters that can be searched. For example I enter no value into the text box and hit enter or click submit and all my database items are displayed. My second issue is simply with the criteria of the search. say I were to search for something like 48 x 12 I would get nothing when in fact there is an item in my database with those characters in the description however they are seperated in this fashion 48 in X 12 in. Lastly is the problem where when I search for results that should produce a message stating that my search returned no results instead I get my blank results table. I'm sure that there are some easy solution and minor tweaks that can be made to my code to rectify some or all of these issues and would appreciate those willing to help to share their knowledge with me. Here is my code: <?php require_once('Connections/price_db.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_Recordset1 = "-1"; if (isset($_GET['title'])) { $colname_Recordset1 = $_GET['title']; } mysql_select_db($database_price_db, $price_db); $query_Recordset1 = sprintf("SELECT * FROM price_db WHERE tb_name LIKE %s OR tb_desc LIKE %s", GetSQLValueString("%" . $colname_Recordset1 . "%", "text"),GetSQLValueString("%" . $colname_Recordset1 . "%", "text")); $Recordset1 = mysql_query($query_Recordset1, $price_db) or die(mysql_error()); $row_Recordset1 = mysql_fetch_assoc($Recordset1); $totalRows_Recordset1 = mysql_num_rows($Recordset1); ?> and the html is as follows: <div id="search_results"> <?php do { ?> <table width="208" border="0" align="left" style="margin-right:20px;"> <tr> <td width="220"><img width="175px" height="175px" src="<?php echo $row_Recordset1['tb_img']; ?>" /></td> </tr> <tr> <td height="45"><h2><?php echo $row_Recordset1['tb_name']; ?></h2> <div id="search_desc"><?php echo $row_Recordset1['tb_desc']; ?></div></td> </tr> <tr> <td height="37"><div id="search_price">$ <?php echo $row_Recordset1['tb_price']; ?> <form action="/save_to_cart.php" method="get" style="padding-top:15px;"> <input type="text" name="quantity" size="10" value="Quantity" style="margin-right:12px; color:#666" onfocus="this.value=''"/> <input type="button" name="Add" value="Select" onclick="this.form.submit()"/> </form> </div></td> </tr> </table> <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?> </body> </html> <?php mysql_free_result($Recordset1); ?> Thanksagain for all help Hello friends,
I am a novice in php. Though I create 2 scripts:
1. students registration form
2. search students by Registration Number
Our students' Registration Numbers are as follows: nifeA001, nifeA002 & so on...
But when someone enter just "nife" or "n" or "A" etc all the students's data is showing.
I want that students can search data by entering only Full Registration Number not a Part.
I am placing the search.php code below. Please help me out....
----------------- Search.php ------------------
<?php
mysql_connect("localhost", "root", "") or die("could not connect");
mysql_select_db("student") or die("could not connect");
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
//here
$query = mysql_query("SELECT * FROM user WHERE registration LIKE '%$searchq%'") or die("could not search!");
$count = mysql_num_rows($query);
if($count == 0){
$output = 'There was no search results!';
}else{
while($row = mysql_fetch_array($query)) {
$fname = $row['firstname'];
$lname = $row['surname'];
$id = $row['registration'];
$output .= '<div> '.$id.' '.$fname.' '.$lname.'</div>';
}
}
}
?>
<html>
<head>
</head>
<body>
<form action="form.php" method="post">
<input type="text" name="search" placeholder="search for students.."
<input type="submit" value=">>" />
</form>
<?php print("$output");?>
</body>
</html>
Edited by NasimUddinAhmmad, 13 January 2015 - 05:43 AM. I found an article on how to implement a mysql search (http://www.iamcal.com/publish/articles/php/search/) and it seemed like a good way to go, but I can't get it up and running. Here is my code: Code: [Select] <?php $db_host = 'localhost'; $db_user = 'username'; $db_pwd = 'password'; $database = 'dbname'; $table = 'Principals'; if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($database)) die("Can't select database"); $searchterms = 'dorr oliver'; function search_split_terms($terms){ $terms = preg_replace("/\"(.*?)\"/e", "search_transform_term('\$1')", $terms); $terms = preg_split("/\s+|,/", $terms); $out = array(); foreach($terms as $term){ $term = preg_replace("/\{WHITESPACE-([0-9]+)\}/e", "chr(\$1)", $term); $term = preg_replace("/\{COMMA\}/", ",", $term); $out[] = $term; } return $out; } function search_transform_term($term){ $term = preg_replace("/(\s)/e", "'{WHITESPACE-'.ord('\$1').'}'", $term); $term = preg_replace("/,/", "{COMMA}", $term); return $term; } function search_escape_rlike($string){ return preg_replace("/([.\[\]*^\$])/", '\\\$1', $string); } function search_db_escape_terms($terms){ $out = array(); foreach($terms as $term){ $out[] = '[[:<:]]'.AddSlashes(search_escape_rlike($term)).'[[:>:]]'; } return $out; } function search_perform($terms){ $terms = search_split_terms($terms); $terms_db = search_db_escape_terms($terms); $terms_rx = search_rx_escape_terms($terms); $parts = array(); foreach($terms_db as $term_db){ $parts[] = "Principals RLIKE '$term_db'"; } $parts = implode(' OR ', $parts); $sql = "SELECT * FROM Principal WHERE $parts"; $rows = array(); $result = mysql_query($sql); while($row = mysql_fetch_array($result, MYSQL_ASSOC)){ $row[score] = 0; foreach($terms_rx as $term_rx){ $row[score] += preg_match_all("/$term_rx/i", $row[Principals], $null); } $rows[] = $row; } uasort($rows, 'search_sort_results'); return $rows; } function search_rx_escape_terms($terms){ $out = array(); foreach($terms as $term){ $out[] = '\b'.preg_quote($term, '/').'\b'; } return $out; } function search_sort_results($a, $b){ $ax = $a[score]; $bx = $b[score]; if ($ax == $bx){ return 0; } return ($ax > $bx) ? -1 : 1; } function search_html_escape_terms($terms){ $out = array(); foreach($terms as $term){ if (preg_match("/\s|,/", $term)){ $out[] = '"'.HtmlSpecialChars($term).'"'; }else{ $out[] = HtmlSpecialChars($term); } } return $out; } function search_pretty_terms($terms_html){ if (count($terms_html) == 1){ return array_pop($terms_html); } $last = array_pop($terms_html); return implode(', ', $terms_html)." and $last"; } # # do the search here... # $results = search_perform($searchterms); $term_list = search_pretty_terms(search_html_escape_terms(search_split_terms($searchterms))); The table name is 'Principals' and the field name I am trying to search is 'Principal'. I am getting an error on the line: while($row = mysql_fetch_array($result, MYSQL_ASSOC)){ The error is: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource Can anyone shed some light on this for me? I wonder whether someone may be able to help me please. I'm trying to put together php code and an html form that allows an administrator to search for a user via the email address, retrieving the 'first' and 'surname' from the pertinent record in a mySQL database. What I would like to happen is for the retrieved 'first' and surname' values to be automatically populated into the 'first' and 'surname' text boxes on the same search form. I can perform the search and retrieval of the correct record without any problem, but I can't work out how to populate the 'first' and 'surname' values into my search form. I am quote a novice with PHP so apologies if this is a really daft question, but I just windered whether somone could take a look at my code below and let me know where I've gone wrong? Many thanks PHP CODE Code: [Select] <?php require("phpfile.php"); // Opens a connection to a MySQL server $connection=mysql_connect ("hostname", $username, $password); if (!$connection) { die('Not connected : ' . mysql_error());} // Set the active MySQL database $db_selected = mysql_select_db($database, $connection); if (!$db_selected) { die ('Can\'t use db : ' . mysql_error()); } $email = $_POST['email']; $result = mysql_query("SELECT * FROM userdetails WHERE emailaddress like '%$email%'"); while($row = mysql_fetch_array($result)) { echo $row['forename']; echo $row['surname']; echo "<br />"; } ?> HTML FORM Code: [Select] !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Maptitle> <script src="js/gen_validatorv4.js" type="text/javascript"></script> </head> <h1><span class="blue">Sign Up</span> For Map My Finds</h1> <form name="userpasswordreset" id="userpasswordreset" method="post" action="search.php"> <h2>Your Details </h2> </div> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="26%" height="25"><strong>Email Address</strong></td> <td width="4%"> </td> <td width="70%"><input name="email" type="email" id="email" size="50" /></td> </tr> <tr> <td height="25"><strong>Confirm Email</strong></td> <td> </td> <td><input name="conf_email" type="email" id="conf_email" size="50" /></td> </tr> <tr> <td height="25"><label> <input type="submit" name="Submit" value="Search" /> </label></td> <td> </td> <td> </td> </tr> <tr> <td height="25"><strong> First Name </strong></td> <td> </td> <td><input name="fname" type="text" id="fname" size="30" value="<?php echo $forename; ?>" /></td> </tr> <tr> <td height="25"><strong> Address Last Name </strong></td> <td> </td> <td><input name="lname" type="text" id="lname" size="30" value="<?php echo $surname; ?>" /></td> </tr> <tr> <td height="25"> </td> <td> </td> <td> </td> </tr> <tr> <td height="25"> </td> <td> </td> <td> </td> </tr> <tr> <td height="25"><strong>Password</strong></td> <td> </td> <td><input name="pass" type="password" id="pass" size="30" /></td> </tr> <tr> <td height="25"><strong>Confirm Password </strong></td> <td> </td> <td><input name="conf_pass" type="password" id="conf_pass" size="30" /></td> </tr> <tr> <td height="25"> </td> <td> </td> <td> </td> </tr> <tr> <td height="25"><strong>Password Hint </strong></td> <td> </td> <td><input name="hint" type="text" id="hint" size="30" /></td> </tr> <tr> <td height="25"> </td> <td> </td> <td> </td> </tr> <tr> <td height="25"> </td> <td> </td> <td> </td> </tr> </table> </form> <script language="JavaScript" type="text/javascript"> // Code for validating the form // Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml // for details var frmvalidator = new Validator("userpasswordreset"); frmvalidator.addValidation("email","req","Please provide your email address"); frmvalidator.addValidation("email","email","Please enter a valid email address"); frmvalidator.addValidation("conf_email","eqelmnt=email", "The confirmed email address is not the same as the email address"); </body> </html> Hey guys, I'm a newbie to PHP and MySql, and I need some help! For the record, I am a web developer and designer, who always put off learning , due to fear, but realized I had to do it. Anyways, my problem is this. I am creating a website, where there has to be a seach box where people can lookup names, and or keywords, that are stored into my db. I've googled it a billion times, and got everything to almost work. I know how to set-up a database, tables, insert info, and all the real basics of mysql. I am running my site on MAMP right now, and here is the code that I am trying to use. <?php /* DON'T DISPLAY ANY PHP ERRORS OR WARNINGS (optional) comment out in development -----------------------------------------------*/ error_reporting(0); /*DATABASE INFO --------------------------*/ $hostname_logon = 'localhost'; //Database server LOCATION $database_logon = ''; //Database NAME $username_logon = ''; //Database USERNAME $password_logon = ''; //Database PASSWORD /*MYSQL TABLE TO SEARCH --------------------------*/ //update these values to table you want to search $db_table = ''; //TABLE NAME $row_id = ''; //TABLE ROW ID $title_field = ''; //FIELD CONTAINING ITEM TITLE $content_field = ''; //FIELD CONTAINING ITEM CONTENT $link_field = ''; //FIELD CONTAINING ITEM URL $limit = 10; //NUMBER OF RESULTS PER PAGE /*SEARCH SCRIPT FILENAME --------------------------*/ //get the name of this file,so you can name this file whatever you want. This is used in the action parameter of the search form $currentFile = $_SERVER["SCRIPT_NAME"]; $parts = explode('/', $currentFile); $currentFile = $parts[count($parts) - 1]; /*CONNECT TO THE DATABASE --------------------------*/ //open database connection $connections = mysql_connect($hostname_logon, $username_logon, $password_logon) or die ( "Unabale to connect to the database" ); //select database mysql_select_db($database_logon) or die ( "Unable to select database!" ); /*GET SEARCH PARAMETERS --------------------------*/ //get the search parameter from URL $var = mysql_real_escape_string(@$_REQUEST['q']); //get pagination $s = mysql_real_escape_string(@$_REQUEST['s']); //set keyword character limit if(strlen($var) < 3){ $resultmsg = "<p>Search Error</p><p>Keywords with less then three characters are omitted...</p>" ; } //trim whitespace from the stored variable $trimmed = trim($var); $trimmed1 = trim($var); //separate key-phrases into keywords $trimmed_array = explode(" ",$trimmed); $trimmed_array1 = explode(" ",$trimmed1); // check for an empty string and display a message. if ($trimmed == "") { $resulterror = "<p>Search Error</p><p>Please enter a search...</p>" ; } // check for a search parameter if (!isset($var)){ $resulterror = "<p>Search Error</p><p>We don't seem to have a search parameter! </p>" ; } //make sure search keyword is at least 2 characters. (buggy if not) if(strlen($trimmed) < 2){ $resulterror = "<p>Search Error</p><p>Your keyword has to be at least two characters long! </p>" ; } /*CREATE SEARCH FORM --------------------------*/ $search_form = '<form class="search-form" action="'.$currentFile.'" method="GET"> <div> <input name="q" type="text" value="'.$q.'"><input name="search" type="submit" value="Search"> </div> </form>'; /*DISPLAY QUERY ERRORS OR DO THE SEARCH --------------------------------------------*/ if($resulterror){ $resultmsg = $resulterror; }else{ // Build SQL Query for each keyword entered foreach ($trimmed_array as $trimm){ // MySQL "MATCH" is used for full-text searching. Please visit mysql for details. $query = "SELECT *, MATCH (".$title_field.",".$content_field.") AGAINST ('".$trimm."') AS score FROM ".$db_table." WHERE MATCH (".$title_field.",".$content_field.") AGAINST ('+".$trimm."' IN BOOLEAN MODE) HAVING score > 0.01 ORDER BY score DESC"; // Execute the query to get number of rows that contain search kewords $numresults=mysql_query ($query) or die ("Error in query: $query. " . mysql_error()); $row_num_links_main =mysql_num_rows ($numresults); //If MATCH query doesn't return any results due to how it works do a search using LIKE if($row_num_links_main < 1){ $query = "SELECT * FROM ".$db_table." WHERE ".$title_field." LIKE '%".$trimm."%' OR ".$content_field." LIKE '%".$trimm."%' ORDER BY ".$row_id." DESC" ; $numresults=mysql_query ($query); $row_num_links_main =mysql_num_rows ($numresults); } // next determine if 's' has been passed to script, if not use 0. // 's' is a variable that gets set as we navigate the search result pages. if (empty($s)) { $s=0; } // now let's get results. $query .= " LIMIT $s,$limit" ; $numresults = mysql_query ($query) or die ("Error in query: $query. " . mysql_error()); $row= mysql_fetch_array ($numresults); //store record id of every item that contains the keyword in the array we need to do this to avoid display of duplicate search result. do{ $adid_array[] = $row[ 'news_id' ]; }while( $row= mysql_fetch_array($numresults)); } //end foreach /*Display a message if no results found --------------------------*/ if($row_num_links_main == 0 && $row_num_links_main1 == 0){ $resultmsg = "<p>Search results for: ". $trimmed."</p><p>Sorry, your search returned zero results</p>" ; } //delete duplicate record id's from the array. To do this we will use array_unique function $tmparr = array_unique($adid_array); $i=0; foreach ($tmparr as $v) { $newarr[$i] = $v; $i++; } //total number of results $row_num_links_main = $row_num_links_main + $row_num_links_main1; if($resultmsg != ""){ $resultmsg = "<p>Search results for: <strong>" . $var."</strong></p>"; } /* FETCH RESULTS BASED ON THE ID --------------------------------------------*/ foreach($newarr as $value){ // EDIT HERE and specify your table and field unique ID for the SQL query $query_value = "SELECT * FROM ".$db_table." WHERE ".$row_id." = '".$value."'"; $num_value=mysql_query ($query_value); $row_linkcat= mysql_fetch_array ($num_value); $row_num_links= mysql_num_rows ($num_value); //create summary of the long text. For example if the field2 is your full text grab only first 130 characters of it for the result $introcontent = strip_tags($row_linkcat[$content_field]); $introcontent = substr($introcontent, 0, 130)."..."; //now let's make the keywods bold. To do that we will use preg_replace function. //Replace field $title = preg_replace ( "'($var)'si" , "<strong>\\1</strong>" , $row_linkcat[ $title_field] ); $desc = preg_replace ( "'($var)'si" , "<strong>\\1</strong>" , $introcontent); //COMMENT OUT THIS LINE: If using database ID field to drive links $link = preg_replace ( "'($var)'si" , "<strong>\\1</strong>" , $row_linkcat[$link_field] ); //UNCOMMENT and EDIT THIS LINE: If using database ID field to drive links //$link = 'http://yourdomain.com/pageid='. $row_linkcat[$link_field]; foreach($trimmed_array as $trimm){ if($trimm != 'b' ){ $title = preg_replace( "'($trimm)'si" , "<strong>\\1</strong>" , $title); $desc = preg_replace( "'($trimm)'si" , "<strong>\\1</strong>" , $desc); $link = preg_replace( "'($trimm)'si" , "<strong>\\1</strong>" , $link); }//end highlight }//end foreach $trimmed_array //format and display search results $resultmsg.= '<div class="search-result">'; $resultmsg.= '<div class="search-title"><a href="'.$link.'">'.$title.'</a></div>'; $resultmsg.= '<div class="search-text">'; $resultmsg.= $desc; $resultmsg.= '</div>'; $resultmsg.= '<a href="'.$link.'" class="search-link">'; $resultmsg.= $link; $resultmsg.= '</a>'; $resultmsg.= '</div>'; } //end foreach $newarr /* CREATE PAGINATION --------------------------------------------*/ if($row_num_links_main > $limit){ // next we need to do the links to other search result pages if ($s >=1) { // do not display previous link if 's' is '0' $prevs=($s-$limit); $resultmsg.= '<div class="search-previous"><a href="'.$PHP_SELF.'?s='.$prevs.'&q='.$var.'">Previous</a></div>'; } // check to see if last page $slimit =$s+$limit; if (!($slimit >= $row_num_links_main) && $row_num_links_main!=1) { // not last page so display next link $n=$s+$limit; $resultmsg.= '<div class="search-next"><a href="'.$PHP_SELF.'?s='.$n.'&q='.$var.'">Next</a></div>'; } }//end if $row_num_links_main > $limit }//end if no errors ?> <?php //display form echo $search_form; //display results echo $resultmsg; ?> I know that this might be asking a lot, but can someone who is smarter than me please give me instructions on how to set this up. I am at a complete loss. I've tried everything. I can connect to the db, and all, but it returns errors, and or blank screens. I will owe everyone. Thank you. Hello I wonder if it is possible to make a search form with different fields where all conditions should be met if the field is set. I have this code: $sel = "SELECT * FROM database "; $sel .= "WHERE ((test1 = '$test1' "; $sel .= "AND test2 = '$test2' "; $sel .= "AND test3 = '$test3' "; $sel .= "ORDER BY id "; $query = mysql_query($sel) or die(mysql_error()); if (mysql_num_rows($query) == 0){ echo ("No result"); exit; When I use this and leave for example 1 field empty I get the error: No result. Is it possible to make smothing so the condition only should be met if the field is set? So If test1 and test3 are set these condition should be met.. I hope you can help! Thanks in advance! - Frederik Hey all, Trying to search for something within a database, using two different fields, one text box and one drop down (the values are actually table names). Here is what I have, this doesn't work: Code: [Select] <?php $result = mysql_query("SELECT * FROM cakeorder WHERE `{$_SESSION['name']}` = '".$_SESSION['search']. "'"); Thanks! Jason Hi, Hoping someone could help me, im not great at php programming and im trying to implement a search form which searches a sql database but for some reason its not working i keep on getting the following error.. " Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\site\contact\search.php on line 141" Im not sure why this happens and its really starting to bug me now :/ I have to pages to the search feature, one page which contains the <form> and the other with the PHP code.... the form.. <form method="get" action="search.php"> <label>Search Term: <input type="text" id="query" name="query"/> </label> <label> <select name="category" id="category"> <option value="none">Please Select a Type</option> <option value="teamname">Manager Name</option> <option value="manager">Team Name</option> <option value="age">Age Group</option> </select> </label> <input name="Search" type="submit" value="Search"/> </form> the PHP code.. <?php $query=$_GET['query']; $db_host="localhost"; $db_username="root"; $db_password=""; $db_name="info"; $db_tb_name="info"; $db_tb_atr_name=$_GET['category']; mysql_connect("$db_host","$db_username","$db_password"); mysql_select_db("$db_name"); $query_for_result=mysql_query("SELECT * FROM $tb_name WHERE $db_tb_atr_name like '%".$query."%'"); while($data_fetch=mysql_fetch_array($query_for_result)) { echo "<p>"; echo $data_fetch['table_attribute']; echo "</p>"; } mysql_close(); ?> Id be really great full for any light you guys could shed on this for me with thanks, fozze |