PHP - Search Issues
I have a search engine that searches through my sql table called `sheets`. Inside this table are the following columns:
id int(11) No artist varchar(100) No title varchar(100) No url varchar(2083) No timesdownloaded int(11) No lastdownloaded date No todaydownloads int(11) No date date No active varchar(3) No duplicate int(1) My search script searches for matches inside the Artist or Title columns. However there is one problem. Let's say I have 5 records (I will show the first three columns): ID .. Artist .. Title 1 .. ABBA .. Super Trouper 2 .. Super Castlevania .. First Stage 3 .. Super Mario Brothers .. Underwater 4 .. Mario .. Theme 5 .. Super Junior .. Sorry, Sorry So if I search for "Super Mario", right now it is displaying the following results (So right now it is searching phrases, rather than single words): 3 .. Super Mario Brothers .. Underwater However, I need to modify my code so it will display the following results: 1 .. ABBA .. Super Trouper 2 .. Super Castlevania .. First Stage 3 .. Super Mario Brothers .. Underwater 4 .. Mario .. Theme 5 .. Super Junior .. Sorry, Sorry Here is my full code, and any suggestions appreciated. I'll be working on it. <?php session_start(); include_once('inc/connect.php'); if (isset($_SESSION['username'])){ $loginstatus = "logout"; } else{ $loginstatus = "login"; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta name="description" content="Free Piano Sheet Music - Sheet Music Haven"> <meta name="keywords" content="free,piano,sheet,music,download,keyboard,haven,lyrics,notes,chords,score,top,modern,popular,jazz,classical,sheetmusichaven"> <meta name="author" content="Sheet Music Haven - Free Piano Sheet Music. Download all types of piano sheet music for free. Popular sheets are added often"> <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"> <title>Search - Sheet Music Haven</title> <link rel="stylesheet" type="text/css" href="styles/style.css"> <script type="text/javascript"> function make_blank() { if(document.login.username.value =="Username"){ document.login.username.value =""; document.login.username.style.color ="#000000"; } } function make_blank1() { if(document.login.password.value =="Password"){ document.login.password.value =""; document.login.password.type ="password"; document.login.password.style.color ="#000000"; } } function undoBlank() { if(document.login.username.value == ""){ document.login.username.value ="Username"; document.login.username.style.color="#ccc"; } } function undoBlankpass() { if(document.login.password.value == ""){ document.login.password.value ="Username"; document.login.password.style.color="#dddddd"; } } </script> </head> <body bgcolor="#343331" OnLoad="document.form.q.focus();"> <?php include('inc/reporterrors.php'); ?> <!-- Header --> <div id="header"> <div id="headerleft"> <div style="position: relative; top: 30px; width: 165px; margin-left: auto; margin-right: auto; text-align: center;"> <form name="form1" action="search.php" method="get"> <div style="float: left;" class="searchboxdiv"><input type="text" name="q" class="searchbox" /></div> <div style="float: right;"><input type="image" src="img/search.png" alt="Search" name="Submit" value="Search" /></div> </form> </div> </div> <div id="headermiddle"><a href="index.php"><img src="img/logo.png"></a></div> <div id="headerright"> <?php echo "<form name='login' action='inc/$loginstatus.php' method='POST'>";?> <div class="loginboxdiv" id="username"> <input type="text" class="loginbox" name="username" value="Username" onFocus="make_blank();" onBlur="undoBlank();"> </div> <div class="loginboxdiv" id="password"> <input class="loginbox" type="text" name="password" type="text" value="Password" onFocus="make_blank1();" onBlur="undoBlankpass();"> </div> <div id="login"> <?php echo "<input type='image' src='img/$loginstatus.png' alt='".ucfirst($loginstatus)."'>";?> </div> </form> <div id="register"> <a href="register.php"><img src="img/register.png"></a> </div> <div id="forgotpassword"> <a href="resetpassword.php" class="forgot">Forgot Password?</a> </div> </div> </div> <!-- Content Top --> <div id="contenttop"> <div id="links"> <table cols="7"> <tr> <td align="center" valign="middle" width="100px" height="48px"><a href="index.php"><img src="img/home.png"></a></td> <td align="center" valign="middle" width="100px" height="48px"><a href="member.php"><img src="img/member.png"></a></td> <td align="center" valign="middle" width="100px" height="48px"><a href="addsheet.php"><img src="img/addsheet.png"></a></td> <td align="center" valign="middle" width="100px" height="48px"><a href="advertise.php"><img src="img/advertise1.png"></a></td> <td align="center" valign="middle" width="100px" height="48px"><a href="faq.php"><img src="img/faq.png"></a></td> <td align="center" valign="middle" width="100px" height="48px"><a href="terms.php"><img src="img/terms.png"></a></td> <td align="center" valign="middle" width="100px" height="48px"><a href="contact.php"><img src="img/contact.png"></a></td> </tr> </table> <!-- 92x30 --> </div> </div> <!-- Content Middle --> <div id="contentmiddle"> <div id="content"> <?php include_once('inc/functions.php'); // Get the search variable from URL $var = @mysql_safe($_GET['q']) ; $trimmed = trim($var); //trim whitespace from the stored variable // rows to return $limit=10000; $date = date("Y-m-d"); $ip = $_SERVER['REMOTE_ADDR']; // check for an empty string and display a message. if ($trimmed == "") { $error = "<tr><td colspan='2' style='text-align: center; border-style: solid; border-color: #f43636; background-color: #fe6a6a;'><strong>Type In A Sheet To Search For</strong></td></tr>"; } // check for a search parameter if (!isset($var)) { $error = "<tr><td colspan='2' style='text-align: center; border-style: solid; border-color: #f43636; background-color: #fe6a6a;'><strong>Type In A Sheet To Search For</strong></td></tr>"; } // Build SQL Query $query = "select * from `sheets` where `active`='yes' AND (artist like \"%$trimmed%\" OR title like \"%$trimmed%\") ORDER BY `artist`"; $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); if ($numrows == 0 || $var=="delete" || $var=="DELETE") { // If search was not found $error = "<tr><td colspan='2' style='text-align: center; border-style: solid; border-color: #f43636; background-color: #fe6a6a;'><strong>Unfortunately that sheet was not found. Please request it by clicking below:</strong></td></tr><tr><td colspan='2' style='text-align: center; border-left-style: solid; border-bottom-style: solid; border-right-style: solid; border-color: #f43636; background-color: #fe6a6a;'>Tip: Keep your search phrase short and simple for best results!</td></tr><tr><td colspan='2' style='text-align: center; border-left-style: solid; border-bottom-style: solid; border-right-style: solid; border-color: #f43636; background-color: #f5f5f5;'><a href='request.php'>Request A Sheet Here</a></td></tr>"; // Insert search phrase ($var) into 'Search' table. id, phrase, date, resultsfound $word = explode(" ", $var); $num = 0; foreach($word as $key=>$value){ $wordexist = mysql_query("SELECT word FROM searchedwords WHERE word='$word[$num]'"); $wordcount = mysql_num_rows($wordexist); if($wordcount!=0){ //UPDATE $wordget = mysql_query("SELECT * FROM searchedwords WHERE word='$word[$num]'"); $wordrow = mysql_fetch_assoc($wordget); $todayword = $wordrow['today']; $totalword = $wordrow['total']; $newtoday = $todayword+1; $newtotal = $totalword+1; $updateword = "UPDATE `searchedwords` SET `today`='$newtoday', `total`='$newtotal' WHERE `word`='$word[$num]'"; mysql_query($updateword); $num++; } else{ $addone = 1; $wordinsert = mysql_query("INSERT INTO searchedwords VALUES ('','$word[$num]','$addone','$addone')"); $num++; } } $searchphrase = mysql_query("INSERT INTO search VALUES ('','$var','$date','no','$ip')"); if($var!=""){ $search = "Search:"; $break = ""; } } else{ // 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"); $search = " "; $break = "<br>"; if($var!=""){ $search = "Search:"; $break = ""; // Insert search phrase ($var) into 'Search' table. id, phrase, date, resultsfound $word = explode(" ", $var); $num = 0; foreach($word as $key=>$value){ $wordexist = mysql_query("SELECT word FROM searchedwords WHERE word='$word[$num]'"); $wordcount = mysql_num_rows($wordexist); if($wordcount!=0){ //UPDATE $wordget = mysql_query("SELECT * FROM searchedwords WHERE word='$word[$num]'"); $wordrow = mysql_fetch_assoc($wordget); $todayword = $wordrow['today']; $totalword = $wordrow['total']; $newtoday = $todayword+1; $newtotal = $totalword+1; $updateword = "UPDATE `searchedwords` SET `today`='$newtoday', `total`='$newtotal' WHERE `word`='$word[$num]'"; mysql_query($updateword); $num++; } else{ $addone = 1; $wordinsert = mysql_query("INSERT INTO searchedwords VALUES ('','$word[$num]','$addone','$addone')"); $num++; } } $searchphrase = mysql_query("INSERT INTO search VALUES ('','$var','$date','yes','$ip')"); } } ?> <br><div id='headsearch'></div> <div style='position: relative; float: left; left: 540px;'><?php if($error==""){echo $numrows." Results";} ?></div> <div style="width: 220px; margin-left: auto; margin-right: auto; text-align: center;"> <form name="form" action="search.php" method="get"> <div style="float: left;"><input type="text" name="q" /></div> <div style="float: right;"><input type="image" src="img/search.png" alt="Search" name="Submit" value="Search" /></div> </form> </div> <?php // display what the person searched for echo "<center><div style='min-width: 210px; margin-left: auto; margin-right: auto; text-align: center;'>$search <span style='color: #6aa504; margin-left; auto; margin-right: auto;'>" . stripslashes($var) . "</span></div></center>"; ?> <?php // begin to show results set $count = 1 + $s ; $greenboxleft = "greenboxleft"; $greenboxright = "greenboxright"; $grayboxleft = "grayboxleft"; $grayboxright = "grayboxright"; $colorvalue = 0; echo "$break<table width='700px' align='center' style='border-collapse:separate; border-spacing:0px;'><th style='background-color: #93DB70; border-bottom-style: solid; border-color: #6aa504;'>Artist</th><th style='background-color: #93DB70; border-bottom-style: solid; border-color: #6aa504;'>Title</th>"; if($error==""){ // now you can display the results returned while ($row= mysql_fetch_array($result)) { $artist = $row["artist"]; $title = $row["title"]; if($artist!="DELETE"){ if(($colorvalue%2)==0){ $styleleft = $greenboxleft; $styleright = $greenboxright; } else{ $styleleft = $grayboxleft; $styleright = $grayboxright; } echo "<tr>"; echo "<td align='center' width='350px' id='$styleleft'><div id='songsboxleft'><strong>". ucwords($row['artist']). "</strong></div></td>"; echo "<td align='center' width='350px' id='$styleright'><div id='songsboxright'><a target='_blank' name='downloadclick' href='download.php?sheet=".$row['url']."&artist=".$row['artist']."&title=".$row['title']."'>" .ucwords($row['title']). "</a></div></td>"; echo "</tr>"; $colorvalue++; } } } else{ echo $error; } echo "</table>"; ?> </div> </div> </div> <!-- Content Bottom --> <div id="contentbottom"> </div> </body> </html> Full Code: Similar TutorialsHi all, a have a small problem with my search script. At the moment I am searching a field in my tabel called searchtags, now if I enter a one word search term of a string of characters it will return the results but if they are not in the same order it won't. Example: searchtags contains - Ford Mondeo 1999 2.0L petrol car If I search "Ford Mondeo" the query returns results, whereas if I search "Mondeo Ford" the query returns no results? I assume I have to expand the search in some way but I don;t know how, any ideas? Thanks in advance Code: [Select] <?php // Get the search variable from URL $var = @$_GET['q'] ; $field = @$_GET['field'] ; $trimmed = trim($var); //trim whitespace from the stored variable if ($field == "") { //if search from homepage start here $query = "select * from fleet where searchtags like \"%$trimmed%\" order by fleetref"; // EDIT HERE and specify your table and field names for the SQL query $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); $limit=10000; if ($numrows == 0) { echo "<p>Sorry, your search: "" . $trimmed . "" motorhomes to hire returned zero results</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 "<h1>You searched for - " . $var . "cars</h1>"; // now you can display the results returned while ($row= mysql_fetch_array($result)) { $fleetref = $row['fleetref']; $fleetmake = $row['fleetmake']; $fleetmodel = $row['fleetmodel']; $fleetyear = $row['fleetyear']; $fleetchassis = $row['fleetchassis']; $fleetberth = $row['fleetberth']; $fleetlayout = $row['fleetlayout']; $fleetlength = $row['fleetlength']; $fleettype = $row['fleettype']; $fleetof = $row['fleetof']; $fleetimage1 = $row['fleetimage1']; $fleetimage2 = $row['fleetimage2']; $fleetimage3 = $row['fleetimage3']; $fleetimage4 = $row['fleetimage4']; $fleetadded = $row['fleetadded']; $fleetengine = $row['fleetengine']; $pricelow = $row['pricelow']; $pricemid = $row['pricemid']; $pricehigh = $row['pricehigh']; $fleetviews = $row['fleetviews']; $query = mysql_query("SELECT * FROM mhhire WHERE `ref` = '$fleetof'"); if(mysql_num_rows($query)==0){ echo "<p>This company does not exsist</p>"; }else{ while($details = mysql_fetch_array($query)){ $company = $details ['company']; $location = $details ['location']; echo "<div class=\"fleet_vehicle\">"; if ($fleetimage1 == "fleet/") { echo "<img src=\"images/no_image.jpg\" alt=\"$fleetmake $fleetmodel\" width=\"100\" height=\"75\" class=\"fleet_thumb\">"; } else { echo "<img src=\"$fleetimage1\" alt=\"$fleetmake $fleetmodel\" width=\"100\" height=\"75\" class=\"fleet_thumb\">"; } echo "<div class=\"fleet_title\">$fleetmake $fleetmodel $fleetyear</div>"; echo "<div class=\"fleet_berth\"><img src=\"images/$fleetberth.gif\" alt=\"$fleetberth berth\"></div>"; echo "<div class=\"fleet_details_in\"><div class=\"fleet_details\">- $fleetberth berth<br />- $fleetlayout<br /></div></div>"; echo "<div class=\"fleet_details_in\"><div class=\"fleet_details\">- $fleetchassis<br />- $fleetengine<br /></div></div>"; echo "<div class=\"fleet_details_in\"><div class=\"fleet_details\">- $fleetlength meters<br />- $fleettype<br /></div></div>"; echo "<div class=\"fleet_options\">From <strong>$company</strong> in <strong>$location</strong> - <a href=\"view_motorhome_for_hire.php?ref=$fleetref\">More info >></a></div>"; echo "</div>"; }} } } ?> when i filter a search it shows 1st page but cannot show contents on 2nd page. i have the following code: <? include_once "connect.php"; if(trim($_REQUEST['searchkeyword'])!="") { $searchkeyword=$_REQUEST['searchkeyword']; $searchkeyword1=str_replace(".", "", $searchkeyword); } if($_REQUEST['stype']!="" && $_REQUEST['start']=="" && trim($_REQUEST['searchkeyword'])!="") { $qry="INSERT INTO search_history set search_type='".$_REQUEST['stype']."', search_text='".$_REQUEST['searchkeyword']."', search_date=now(), result_url='course_listing.php?searchkeyword=".$_REQUEST['searchkeyword']."'"; mysql_query($qry); $_GET['stype']=""; } $PVR_SectionID="2"; $extQry=""; $extQry2=""; if(isset($_REQUEST['searchkeyword'])) { $extQry.=" and (department like '%".$_REQUEST['searchkeyword']."%' or course_title like '%".$searchkeyword1."%' or course_title like '%".$_REQUEST['searchkeyword']."%' or course_desc like '%".$_REQUEST['searchkeyword']."%')"; $extQry2=" and (name like '%".$_REQUEST['searchkeyword']."%' or contact_name like '%".$_REQUEST['searchkeyword']."%' or country like '%".$_REQUEST['searchkeyword']."%' or city like '%".$_REQUEST['searchkeyword']."%' or description like '%".$_REQUEST['searchkeyword']."%')"; } if(isset($_REQUEST['subject'])) { $extQry.=" and sub_id in ("; $cnt=0; foreach($_REQUEST['subject'] as $k=>$v) { $cnt++; if($cnt>1) { $extQry.=",".$v; } else { $extQry.=$v; } } $extQry.=") "; } if(isset($_REQUEST['region'])) { $extQry.=" and uni_id in (SELECT id from institution where is_active='1' and reg_id in("; $extQry2.=" and reg_id in("; $cnt=0; foreach($_REQUEST['region'] as $k=>$v) { $cnt++; if($cnt>1) { $extQry.=",".$v; $extQry2.=",".$v; } else { $extQry.=$v; $extQry2.=$v; } } $extQry.=") ) "; $extQry2.=")"; } if(isset($_REQUEST['studymode'])) { $extQry.=" and id in ( SELECT course_id from course_qdm where mode in ("; $cnt=0; foreach($_REQUEST['studymode'] as $k=>$v) { $cnt++; if($cnt>1) { $extQry.=",'".$v."'"; } else { $extQry.="'".$v."'"; } } $extQry.=") ) "; } if(isset($_REQUEST['institution'])) { $extQry.=" and uni_id='".$_REQUEST['institution']."'"; } $courseQry="SELECT * FROM course where is_active='1' $extQry "; $crsRes=mysql_query($courseQry); $totCourse=mysql_affected_rows(); $pgLimit=10; $shFrom=intval($_REQUEST['start'])+1; $shTo= $shFrom + $pgLimit - 1; if($shTo>$totCourse) $shTo=$totCourse; $CRSresult=$prs_pageing->number_pageing22($courseQry,$pgLimit,10,'N','Y'); $courseQry="SELECT * FROM institution where is_active='1' $extQry2"; $instRes=mysql_query($courseQry); $totInstitution=mysql_affected_rows(); ?> <!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" /> <? getMeta("4") ;?> <?php include("head_script.php"); ?> <script src="../../../../DOCUME~1/Farhan/LOCALS~1/Temp/Scripts/cforms.js" type="text/javascript"></script> <script src="../../../../DOCUME~1/Farhan/LOCALS~1/Temp/SpryAssets/SpryAccordion.js" type="text/javascript"></script> <script type="text/javascript"> <!-- function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } //--> </script> <link href="../../../../DOCUME~1/Farhan/LOCALS~1/Temp/SpryAssets/SpryAccordion.css" rel="stylesheet" type="text/css" /> </head> <body> <table width="950" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td><? include_once "header.php"; ?></td> </tr> <tr> <td><table width="950" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="753" height="32"><div id="track_2"><a href="../../../../DOCUME~1/Farhan/LOCALS~1/Temp/index.php" style="padding-left:0px;"><img src="../../../../DOCUME~1/Farhan/LOCALS~1/Temp/images/btn_home.gif" /></a><a href="../../../../DOCUME~1/Farhan/LOCALS~1/Temp/course_search.php">Find courses and research</a><span>Search Results</span></div></td> <td width="10" rowspan="2"> </td> <td width="187" rowspan="2" align="center" valign="top" bgcolor="#f9f9f9"><? include_once "banners_block.php"; ?></td> </tr> <tr> <td valign="top" id="contents"> <h1>you have <?=$totCourse;?> Course Search Result</h1> <? include "course_filter.php"; ?> <? if($CRSresult[1]!="") { ?> <div> <h2>Showing <?=$shFrom;?>-<?=$shTo;?></h2></div> <? while($CRSrow=mysql_fetch_array($CRSresult[0])) { ?> <div class="mix"> <a href="<?=course_details_URL($CRSrow['id']);?>"><b><?=stripslashes($CRSrow['course_title']);?></b></a> <? $quaRes=mysql_query("SELECT qualification from course_qdm where course_id='".$CRSrow['id']."'"); if(mysql_affected_rows()>0) { $cnt=0; $qArr=array(); while($quaRow=mysql_fetch_array($quaRes)) { if(!array_key_exists($quaRow['qualification'],$qArr)) { $cnt++; if($cnt>1) { echo " / ".stripslashes($quaRow['qualification']); } else { echo stripslashes($quaRow['qualification']); } $qArr[$quaRow['qualification']]=1; } } } ?> <a href="<?=university_prof_details_URL($CRSrow['uni_id']);?>" ><strong><?=stripslashes(GetValue("institution","name","id",$CRSrow['uni_id']));?></strong></a> - <?=stripslashes($CRSrow['department']);?> <br /> <span><?=substr(strip_tags(stripslashes($CRSrow['course_desc'])),0,100);?>...</span> <a href="<?=course_details_URL($CRSrow['id']);?>"><strong>read more</strong></a> </div> <? } ?> <?php $sub_get = $_GET['subject']; $s_pass = $sub_get[0]; ?> <?php /*?><div class="link_large"><a href="all_course.php?q=<?=base64_encode($extQry);?>">More Courses</a></div><?php */?> <? } ?> <div> <?=$CRSresult[1];?> </div> </td> </tr> </table></td> </tr> <tr> <td><? include_once "bookmark.php"; ?></td> </tr> <tr> <td><? include_once "footer.php"; ?></td> </tr> </table> </body> </html> i have an issue in plain php when i filter my search result for specific search it shows 1st page but can not give results on 2nd page i am sending both the files includes: course_listing.php course_filter.php 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 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. 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 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> 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 Hello All, 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? 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! Hey all, I can not get utf-8 working properly. I'm having issues with special characters, such as bullets, e with an accent over it, etc. The data is being stored in my mssql database properly, and I can see everything there fine. It's when I grab it from the database and display it on my php page. The page it set up to utf-8, if I go to Tools>Page Info, it says encoding is utf-8. I have it in my headers, I just can not figure out why it will not display on the page. Any thoughts? Issue # 1 How can i send the values come from $_POST['name'],$_POST['number'] to an email address xyz@radiations3.com??? Issue # 2 I am trying to display data from four different tables with the following sql query: (The problem is that the data is getting displayed fine but i don't know why some of the (same )data gets repeated two or three times where as i checked in all four tables and all the data exists one time not twice) If anything wrong with my query kindly help SELECT distinct * FROM applicant,applicant_info_nic,room,student WHERE applicant_info_nic.status='Available' and applicant.appNIC=applicant_info_nic.appNIC and applicant.roomID=room.roomID and applicant.appNIC=student.appNIC ORDER BY applicant.roomID i am trying to sort out a session now, i normally use the folllowing code to check if someone is logged in and if they are not to forward them to the login page, but i am getting this message: Notice: Undefined index: username in code: Code: [Select] if ($_SESSION['username']) { }else{ include 'login.php'; die(""); } can someone help please. Hello, I'm having troubles parsing text properly. Whenever I submit data into a mysql db, and then call that specific data, in the text, I get this symbol, �. Does anybody know what it is or how to remove it? I believe it's with utf-8 and me using a function that corrupts the string but I'm not sure. Anybody have any clues? Thanks in advance. Hi folks, me again. I am trying to create the login for the admin section of my project, but facing issues again. I can't seem to get the code to check to see if the username and password submitted through the login form is correct as per what is in the database. Here is the form: Code: [Select] <form action="authenticate.php" method="post" name="frmLogin" id="frmLogin"> <table width="400" border="1" align="center" cellpadding="2" cellspacing="2"> <tr> <td width="150">User Id</td> <td><input name="txtUserId" type="text" id="txtUserId"></td> </tr> <tr> <td width="150">Password</td> <td><input name="txtPassword" type="password" id="txtPassword"></td> </tr> <tr> <td width="150"> </td> <td><input name="btnLogin" type="submit" id="btnLogin" value="Login"></td> </tr> </table> </form> The authenticate.php: <?php session_start(); // Start a new session require('../config/config.php'); // Holds all of our database connection information // Get the data passed from the form $username = $_POST['user']; $password = $_POST['password']; // Do some basic sanitizing $username = stripslashes($username); $password = stripslashes($password); $sql = "select * from users where username = '$username' and password = '$password'"; $result = mysql_query($sql) or die ( mysql_error() ); $count = 0; while ($line = mysql_fetch_assoc($result)) { $count++; } ?> The errors I get: Code: [Select] Warning: mysql_query() [function.mysql-query]: Access denied for user 'danoid'@'localhost' (using password: NO) in /home/danoid/public_html/admin/authenticate.php on line 14 Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/danoid/public_html/admin/authenticate.php on line 14 Access denied for user 'danoid'@'localhost' (using password: NO) Any one got any ideas? |