PHP - I Have Code To Search A Database Of Members, I Can Search By Lastname :
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> Similar TutorialsI 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 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! The result pages is supposed to have pagination like google help me please
it is displaying the lastnames in the order they are in the profile but do not know how to get it to sort by lastname - please help <?php $lines = file('database/profile.txt'); foreach($lines as $thisline){list($p_id,$p_status,$p_filestart,$p_filemodified,$p_first,$p_middle,$p_last,$p_nick) = explode('|',$thisline);{ $names []= $p_last.', '.$p_first.' '.$p_middle.'.'; foreach($names as $value); {echo ''.$value.'<br>';}}} ?> 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 Hello all. First of all, if this isn't the right place for this topic, please excuse me and may the moderators/admins move it where it should belong. Second, I'm trying to make a mysql search - Everything works, but if say, a user searches for 34 it displays all numbers that have the number 34 in them. I want the results to be exact - if a user searches for 34, to display only 34, not 334, 5034 or 3401 (like it happens now). Here's the code: Code: [Select] <?php mysql_connect ("**************", "*******","*****") or die (mysql_error()); mysql_select_db ("********"); $term = $_POST['term']; $sql = mysql_query("select * FROM countries WHERE cocode LIKE '%$term%'"); while ($row = mysql_fetch_array($sql)){ echo '<br/> Code: '.$row['cocode']; echo '<br/> Country: '.$row['coname']; echo '<br/><br/>'; } ?> If you have any questions, you're welcome to ask them in the thread. Thank you in advance Hi i am an absolute PHP/MYSQL Novice but i guess we all gotta start somewhere. I have a table in my database with names and addresses, f_name, s_name, street, zip_code, city etc etc etc What i want to do is display a drop down of all cities in my database then click on any city in the list to display all the details of people in that city, showing all fields. So i have got this far .. Code: [Select] $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); $dbname = 'cities_wrdp1'; mysql_select_db($dbname); $sql = "SELECT DISTINCT City FROM PBM"; $result = mysql_query($sql); echo "<select name='City'>"; while ($row = mysql_fetch_array($result)) { echo "<option value='" . $row['City'] . "'>" . $row['City'] . "</option>"; } echo "</select>"; This produces the nice drop down list of cities from the database ... Now on click i would like to return results similar to this Code: [Select] $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); $dbname = 'cities_wrdp1'; mysql_select_db($dbname); $query = sprintf("SELECT * FROM PBM"); $result = mysql_query($query); if (!$result) { $message = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message); } echo "<br />"; echo "<table border='0'>"; while ($row = mysql_fetch_assoc($result)) { echo "<tr><td>"; echo "<a href=\"" .$row['profileURL'] . "\"> <img src=\"" . $row['faviconURL'] . "\" border=0 alt=\"" . $row["Thumbnail"] . "\"> </a>"; echo "</td><td align='center'>"; echo $row['f_name']; echo "</td><td align='center'>"; echo $row['s_name']; echo "</td><td align='center'>"; echo $row['number']; echo "</td><td align='center'>"; echo $row['street']; echo "</td><td align='center'>"; echo $row['zip']; echo "</td><td align='center'>"; echo $row['city']; echo "</td><td align='center'>"; echo $row['Country']; echo "</td><td align='center'>"; echo $row['email_address']; echo "</td><td align='center'>"; echo $row['fb']; echo "</td><td align='center'>"; echo $row['web_site']; echo "</td><td align='center'>"; echo $row['phone']; echo "</td><td align='center'>"; echo $row['land']; echo "</td><td align='center'>"; echo $row['age']; echo "</td></tr>"; } echo "</table>"; mysql_free_result($result); So my question is .. how do i make the first piece of code selectable to produce similar results to the second piece of code based on the city selected ? Thanks for any help .. and please excuse my ignorance .. 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 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 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 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 Could somebody help me with a little problem I am having, I havew spent the last two weeks trying different ways to search my database without success. What I want to do is have an input field that I can search only one column of my database. (it is a game collection) for example I want to search the game 'Medal of Honor' i type this in the search field and click submit button and it should find all the entries with that name in the database. I have tried a few online tutorials and nothing works.
here is some code that i tried. <?php $host = "localhost"; $user = "root"; $password =""; $database = "csv_db"; $id = ""; $game = ""; $year = ""; $platform = ""; mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // connect to mysql database try{ $connect = mysqli_connect($host, $user, $password, $database); } catch (mysqli_sql_exception $ex) { echo 'Error'; } // get values from the form function getPosts() { $posts = array(); $posts[0] = $_POST['id']; $posts[1] = $_POST['game']; $posts[2] = $_POST['year']; $posts[3] = $_POST['platform']; return $posts; } // Search if(isset($_POST['search'])) { $data = getPosts(); $search_Query = "SELECT * FROM games WHERE id = $data[0]"; $search_Result = mysqli_query($connect, $search_Query); if($search_Result) { if(mysqli_num_rows($search_Result)) { while($row = mysqli_fetch_array($search_Result)) { $id = $row['ID']; $game = $row['GAME']; $year = $row['YR']; $platform = $row['PLATFORM']; } }else{ echo 'No Data For This Id'; } }else{ echo 'Result Error'; } } // Insert if(isset($_POST['insert'])) { $data = getPosts(); $insert_Query = "INSERT INTO `games`(`Game`, `YR`, `PLATFORM`) VALUES ('$data[1]','$data[2]',$data[3])"; try{ $insert_Result = mysqli_query($connect, $insert_Query); if($insert_Result) { if(mysqli_affected_rows($connect) > 0) { echo 'Data Inserted'; }else{ echo 'Data Not Inserted'; } } } catch (Exception $ex) { echo 'Error Insert '.$ex->getMessage(); } } // Delete if(isset($_POST['delete'])) { $data = getPosts(); $delete_Query = "DELETE FROM `games` WHERE `ID` = $data[0]"; try{ $delete_Result = mysqli_query($connect, $delete_Query); if($delete_Result) { if(mysqli_affected_rows($connect) > 0) { echo 'Data Deleted'; }else{ echo 'Data Not Deleted'; } } } catch (Exception $ex) { echo 'Error Delete '.$ex->getMessage(); } } // Edit if(isset($_POST['update'])) { $data = getPosts(); $update_Query = "UPDATE `games` SET `GAMES`='$data[1]',`YR`='$data[2]',`PLATFORM`=$data[3] WHERE `ID` = $data[0]"; try{ $update_Result = mysqli_query($connect, $update_Query); if($update_Result) { if(mysqli_affected_rows($connect) > 0) { echo 'Data Updated'; }else{ echo 'Data Not Updated'; } } } catch (Exception $ex) { echo 'Error Update '.$ex->getMessage(); } } ?> <!DOCTYPE Html> <html> <head> <title>PHP INSERT UPDATE DELETE SEARCH</title> </head> <body> <form action="php_insert_update_delete_search.php" method="post"> <input type="number" name="id" placeholder="ID" value="<?php echo $id;?>"><br><br> <input type="text" name="game" placeholder="Game" value="<?php echo $game;?>"><br><br> <input type="text" name="year" placeholder="Year" value="<?php echo $year;?>"><br><br> <input type="number" name="platform" placeholder="Platform" value="<?php echo $platform;?>"><br><br> <div> <!-- Input For Add Values To Database--> <input type="submit" name="insert" value="Add"> <!-- Input For Edit Values --> <input type="submit" name="update" value="Update"> <!-- Input For Clear Values --> <input type="submit" name="delete" value="Delete"> <!-- Input For Find Values With The given ID --> <input type="submit" name="search" value="Find"> </div> </form> </body> </html> and here is the error i get. Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1 in H:\xampp\htdocs\php_insert_update_delete_search.php:41 Stack trace: #0 H:\xampp\htdocs\php_insert_update_delete_search.php(41): mysqli_query(Object(mysqli), 'SELECT * FROM g...') #1 {main} thrown in H:\xampp\htdocs\php_insert_update_delete_search.php on line 41 can anybody help me do I search engine for my database Hey guys, Hi all. This is the code I've been trying to execute. <?php // Get the search variable from URL $var = @$_GET['q'] ; $trimmed = trim($var); //trim whitespace from the stored variable // rows to return $limit=10; // check for an empty string and display a message. if ($trimmed == "") { echo "<p>Please enter a search...</p>"; exit; } // check for a search parameter if (!isset($var)) { echo "<p>No search parameter</p>"; exit; } //connect to your database ** EDIT REQUIRED HERE ** mysql_connect("localhost","*","*"); //(host, username, password) //specify database ** EDIT REQUIRED HERE ** mysql_select_db("my_db") or die("Can't select database//Does not exist."); //select which database we're using // Build SQL Query $query = "select * from people \"%$trimmed%\" order by FirstName"; // EDIT HERE and specify your table and field names for the SQL query $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); // If we have no results, offer a google search as an alternative if ($numrows == 0) { echo "<h4>Results</h4>"; echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>"; echo "<p><a href=\"http://www.google.com/search?q=" . $trimmed . "\" target=\"_blank\" title=\"Look up " . $trimmed . " on Google\">Click here</a> to try the search on Google</p>"; } // next determine if s has been passed to script, if not use 0 if (empty($s)) { $s=0; } // get results $query .= " limit $s,$limit"; $result = mysql_query($query) or die("Couldn't execute query"); // display what the person searched for echo "<p>You searched for: "" . $var . ""</p>"; // begin to show results set echo "Results"; $count = 1 + $s ; // now you can display the results returned while ($row= mysql_fetch_array($result)) { $title = $row["FirstName"]; echo "$count.) $title" ; $count++ ; } $currPage = (($s/$limit) + 1); //break before paging echo "<br />"; // next we need to do the links to other results if ($s>=1) { // bypass PREV link if s is 0 $prevs=($s-$limit); print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><< Prev 10</a>  "; } // calculate number of pages needing links $pages=intval($numrows/$limit); // $pages now contains int of pages needed unless there is a remainder from division if ($numrows%$limit) { // has remainder so add one page $pages++; } // check to see if last page if (!((($s+$limit)/$limit)==$pages) && $pages!=1) { // not last page so give NEXT link $news=$s+$limit; echo " <a href=\"$PHP_SELF?s=$news&q=$var\">Next 10 >></a>"; } $a = $s + ($limit) ; if ($a > $numrows) { $a = $numrows ; } $b = $s + 1 ; echo "<p>Showing results $b to $a of $numrows</p>"; ?> As you can see, it's pretty simple and it's got very nice explanations of what everything does. But when I try it, I get this. Quote Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in D:\Program Files\xampp\xampp\htdocs\search.php on line 36 Results Sorry, your search: "Ella" returned zero results Click here to try the search on Google Couldn't execute query I'm pretty much stuck. Any ideas what that error means? And yes, there is a entry with the name of Ella in the people table of the database. Help? i have enters some data using form which submit data in sql table1 like this, Fields name in table -->> id First name Lastname Date data saved -->> 1 user 1 2011-05-10 2 user 2 2011-05-11 3 user 3 2011-05-12 now i dont want to duplicate date in database let say while inserting data using form, Firstname : ____________ Lasename : ____________ Date : ____________ (i dont want this date to b save if the date alredy exist in database, it should prompt user "Date already exist and to edit click here (this will be the link to that date which is already exist so that we can edit) " ) SAVE i user files , form.php , insert.php(so insert values in database) , so tell me what function should i use to solve my problem.... Hello, so i made table with Tags row which is Text(126).. and idea is to put text like "PHP, MySQL, Forum, Blog" etc etc...
I have problem searching tags my search code:
$requestedtag = $con->real_escape_string($_GET['tag']); $sql = "SELECT * FROM images WHERE tags = '$requestedtag' ORDER BY ID DESC LIMIT 12"; $result = $con->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $image_id = $row["ID"]; $image_title = $row["Title"]; $image_url = $row["ImgURL"]; $image_tags = $row["Tags"]; echo '<div class="col-3"><div class="thumb"><a href="/image.php?id='.$image_id.'" title="'.$image_title.'"><img src="'.$image_url.'"></img></a></div></div>'; } } But it doesnt return anything. I think the problem is that row["Tags"]; is divided by "," from tags and i should split it somehow but i dont really know what to do... I found this nice search database script on line but the pagination does not work can someone tell me what is wrong with it ???? so i can work with it !!! here is the full code : Code: [Select] <?php // Get the search variable from URL $var = @$_GET['q'] ; $trimmed = trim($var); //trim whitespace from the stored variable // rows to return $limit=10; // check for an empty string and display a message. if ($trimmed == "") { echo "<p>Please enter a search...</p>"; exit; } // check for a search parameter if (!isset($var)) { echo "<p>We dont seem to have a search parameter!</p>"; exit; } //connect to your database ** EDIT REQUIRED HERE ** mysql_connect("localhost","username","password"); //(host, username, password) //specify database ** EDIT REQUIRED HERE ** mysql_select_db("database") or die("Unable to select database"); //select which database we're using // Build SQL Query $query = "select * from the_table where 1st_field like \"%$trimmed%\" order by 1st_field"; // EDIT HERE and specify your table and field names for the SQL query $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); // If we have no results, offer a google search as an alternative if ($numrows == 0) { echo "<h4>Results</h4>"; echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>"; echo "<p><a href=\"http://www.google.com/search?q=" . $trimmed . "\" target=\"_blank\" title=\"Look up " . $trimmed . " on Google\">Click here</a> to try the search on google</p>"; } // next determine if s has been passed to script, if not use 0 if (empty($s)) { $s=0; } // get results $query .= " limit $s,$limit"; $result = mysql_query($query) or die("Couldn't execute query"); // display what the person searched for echo "<p>You searched for: "" . $var . ""</p>"; // begin to show results set echo "Results"; $count = 1 + $s ; // now you can display the results returned while ($row= mysql_fetch_array($result)) { $title = $row["1st_field"]; echo "$count.) $title" ; $count++ ; } $currPage = (($s/$limit) + 1); //break before paging echo "<br />"; // next we need to do the links to other results if ($s>=1) { // bypass PREV link if s is 0 $prevs=($s-$limit); print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><< Prev 10</a>  "; } // calculate number of pages needing links $pages=intval($numrows/$limit); // $pages now contains int of pages needed unless there is a remainder from division if ($numrows%$limit) { // has remainder so add one page $pages++; } // check to see if last page if (!((($s+$limit)/$limit)==$pages) && $pages!=1) { // not last page so give NEXT link $news=$s+$limit; echo " <a href=\"$PHP_SELF?s=$news&q=$var\">Next 10 >></a>"; } $a = $s + ($limit) ; if ($a > $numrows) { $a = $numrows ; } $b = $s + 1 ; echo "<p>Showing results $b to $a of $numrows</p>"; ?> Can someone please double check my search query to make sure it is the minimum and most efficient coding. My goal is an exact match search of field1 from my database table and list field1, field2, field3, field4 and field5 if the part number is in the database or no results if it is not. The query works as is but I have a feeling it could be done more efficiently or professionally and minimum work for my poor little server. Thanks in advance. Code: [Select] <?php //connect to the database include("./databaseconnect.php"); //get query $q=$_GET['q']; //convert query to uppercase & remove all spaces and special charactars $q=strtoupper(preg_replace("/[^A-Za-z0-9]/","",$q)); //if blank query if ($q == "") { echo "You did not enter a search term"; } else { //exact match only query $query = "SELECT * FROM ".$dbtable." WHERE field1 like \"$q\""; $result = mysql_query($query); //if query returns no results if(mysql_num_rows($result)==0) { echo "<span class=\"noresults\">There were no results for your search</span>"; //display database results } else { while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "<span class=\'results\'>SEARCH RESULTS</span><br /> <span class=\'list\'>Part Number: ".$row['field1']."<br /> Manufacturer: ".$row['field2']."<br /> Cost per unit: ".$row['field3']."<br /> Warehouse Location: ".$row['field4']."<br /> Quantity Available: ".$row['field5']."<br /> Notes: ".$row['field6']."<br /> </span>"; } } } ?> <?php if(isset($_POST['ActivityId'])) { require_once('database.php'); $Search=$_POST['Search']; $query="select * from registration where Flag='A' AND Activity like '%,$Search,%'"; $result=mysqli_query($dbc,$query) or die('Not Connected'); while($row=mysqli_fetch_array($result)) { echo "<table border='2'><tr><td> Name--".$row['Name']."</td> <td>Contact Number--".$row['ContactNumber']."</td> <td>Email--".$row['Email']."</td> <td>Address--".$row['Address']."</td></tr></table>"; } } elseif(isset($_POST['EventId'])){ require_once('database.php'); $Search=$_POST['Search']; $query="select * from participation where EventId ='$Search'"; $result=mysqli_query($dbc,$query) or die('Not Connected'); while($row=mysqli_fetch_array($result)){ $LoginId= $row['LoginId']; echo $LoginId;} $query="select * from registration where LoginId='$LoginId'"; $result=mysqli_query($dbc,$query) or die('Not Connected to Reg'); while($row=mysqli_fetch_array($result)){ echo "<table border='2'><tr><td> Name--".$row['Name']."</td> <td>Contact Number--".$row['ContactNumber']."</td> <td>Email--".$row['Email']."</td> <td>Address--".$row['Address']."</td></tr></table>"; }} elseif(isset($_POST['Location'])) { require_once('database.php'); $Search=$_POST['Search']; $query="select * from registration where Flag='A' AND Address like '%$Search%'"; $result=mysqli_query($dbc,$query) or die('Not Connected'); while($row=mysqli_fetch_array($result)) { echo "<table border='2'><tr><td> Name--".$row['Name']."</td> <td>Contact Number--".$row['ContactNumber']."</td> <td>Email--".$row['Email']."</td> <td>Address--".$row['Address']."</td></tr></table>"; } } elseif(isset($_POST['BloodGroup'])) { require_once('database.php'); $Search=$_POST['Search']; $query="select * from registration where Flag='A' AND BloodGroup ='$Search'"; $result=mysqli_query($dbc,$query) or die('Not Connected'); while($row=mysqli_fetch_array($result)) { echo "<table border='2'><tr><td> Name--".$row['Name']."</td> <td>Contact Number--".$row['ContactNumber']."</td> <td>Email--".$row['Email']."</td> <td>Address--".$row['Address']."</td></tr></table>"; } } ?> <html><body><form action='<?php echo $_SERVER['PHP_SELF']?>' method="post"> <input type="text" name="Search"><br> <input type="submit" name="ActivityId" value="Submit Activity Id"><br> <input type="submit" name="EventId" value="Submit Event Id"><br> <input type="submit" name="Location" value="Submit Location"><br> <input type="submit" name="BloodGroup" value="Submit Blood Group"><br> </form> </body></html> Hi frds............. I have two tables named "registration" and "participation". Registration table have some columns like "LoginId", "email","contact no.", "Name" etc.and participation table have 2 column named "LoginId" and "EventId". Now if user enters EventId, I want to display the details like email,contact no. etc. I have a code but it not works properly....... If result have more than one row it only displays the email and contact no. of last one instead of all. Plzzzzzzzzz help anyone................... ????????/ |