PHP - Some Problems With Search Query
Hi,
i have the following problem. I use a script to enter data in a mysql database and for now i only have three variable... Quote <h2>Invoeren</h2> <form action="insert.php" method="post" class="cmxform"> <fieldset> <legend>Gegevens</legend> <table border="2"> <tr> <td>1. </td> <td><label for="merk">merk:</label></td> <td><input id="merk" name="merk" /></td> </tr> <tr> <td>2. </td> <td><label for="cpu">cpu:</label></td> <td><select name="cpu" id="cpu" /> <option value="">Maakt niet uit</option> <option value="amd">amd</option> <option value="intel">intel</option> </select></td> </tr> <tr> <td>3. </td> <td><label for="hdd">hdd:</label></td> <td><select name="hdd" id="hdd" /> <option value="">Maakt niet uit</option> <option value="160GB">160GB</option> <option value="320GB">320GB</option> <option value="500GB">500GB</option> </select></td> </tr> </table> <input type="submit" value="Verstuur" /> </fieldset> </form> Data goes in to the database correctly but now i use the following search script... Quote <h2>zoeken</h2> <form action="search.php" method="post" class="cmxform"> <fieldset> <legend>Gegevens</legend> <table border="2"> <tr> <td>1. </td> <td><label for="merk">merk:</label></td> <td><input id="merk" name="merk" /></td> </tr> <tr> <td>2. </td> <td><label for="cpu">cpu:</label></td> <td><select name="cpu" id="cpu" /> <option value="0">Maakt niet uit</option> <option value="amd">amd</option> <option value="intel">intel</option> </select></td> </tr> <tr> <td>3. </td> <td><label for="hdd">hdd:</label></td> <td><select name="hdd" id="hdd" /> <option value="0">Maakt niet uit</option> <option value="160GB">160GB</option> <option value="320GB">320GB</option> <option value="500GB">500GB</option> </select></td> </tr> </table> <input type="submit" value="Verstuur" /> </fieldset> </form> The values go correct to the search script because i checked this with an echo function. The search.php loks like this Quote <?php $con = mysql_connect("localhost","admin","t1tan1um"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("model", $con); $qry = "SELECT * FROM eigenschappen WHERE 1=1"; if (isset($_POST['merk']) && $_POST['merk'] != 0) { $qry .= " AND merk='" . mysql_real_escape_string($_POST['merk']). "'"; } if (isset($_POST['cpu']) && $_POST['cpu'] != 0) { $qry .= " AND cpu='" . mysql_real_escape_string($_POST['cpu']). "'"; } if (isset($_POST['hdd']) && $_POST['hdd'] != 0) { $qry .= " AND hdd='" . mysql_real_escape_string($_POST['hdd']). "'"; } $result = mysql_query($qry) or die(mysql_error()); // lelijke foutmelding, zelf mooier maken of $result door een if statement halen while($row = mysql_fetch_array($result)) { echo $row['merk'] . " " . $row['cpu'] . " " . $row['hdd']; echo "<br />"; } ?> When i search for hdd wich is last in de search list the query only returns the records wich contain that value. When the condition has to be for example Intel cpu AND 500GB it returns everyting with 500GB but also every kind of CPU. Anyone? Similar TutorialsHi All. I am looking to search a database of products based upon someone typing the name of the product they are looking for. I am using the below SQL request: Unfortunately this only shows what ever your typing and anything before or after (%) is there any way that it could also search unplaced string instances? For example $q = "SELECT * FROM products WHERE prod_name LIKE '%$id%' order by fee asc LIMIT 20"; If i type black ops ps3 it brings back search result until i get to the PS3 part. because entries in the db are "black ops for the PS3" because i havent conformed it says no results. I need it to show all results. is there another way? or can someone point me in the right direction? Hi everyone! So, this is probably one of the most simplest things to all you pros out there, but unfortunately I think I'm using the wrong words in Google as I can't seem to remember what they're called (Yeah I'm not that brilliant.) Anyway, a quick one for you guys. What I'm looking for is a simple script or method to send a Search Query to end with a URL. For example. Lets say I'm on http://mysite.com/index.php, and on that page is a search box. Now, lets say I search the word "Pizza" in that search box. I want the end result to be "http://myspace.com/search.php?s=pizza" I already have the script I'd like to use to read that value, I just simply don't know how to put that value there in the first. Yes, I know, noobish question, I'm sorry. XD Thanks in advance! This is for a faux stock photo website. When I only use the $query string to search for $searchSubject, everything goes golden. Once I put everything else in there though, the search function will not work at all. Any help will be greatly appreciated. I've been staring at this for too long and it's starting to give me a headache. PS. This is my first post here. Seems like a great community! <?php $searchSubject = $_POST['searchSubject']; $searchPhotoname = $_POST['searchPhotoname']; $searchLocation = $_POST['searchLocation']; if (isset($_POST['search'])) { //Select records from the database $query = "SELECT * FROM `photos` WHERE `subject` LIKE '%" . $searchSubject . "%' OR `name` LIKE '%" . $searchPhotoname . "%' OR `location` LIKE '%" . $searchLocation . "%' "; } else { $query = "SELECT * FROM photos"; } $result = mysql_query($query); // count the number of rows in the database $num = mysql_num_rows($result); ?> If I leave it at this: $query = "SELECT * FROM `photos` WHERE `subject` LIKE '%" . $searchSubject . "%'"; Then everything works perfect. Hello, I can't really explain it so a example will be better: my_table: col1 col2 col3 col4 1 1 23 A 2 1 25 A 3 2 21 B 4 3 24 A 5 3 28 A the query is-- SELECT col3 FROM my_table WHERE col2=SELECT(MAX(col2) FROM my_table WHERE col4='A') For some reason this is illegal, I can also not use a limit because the number of rows is not known a priori. I remember seeing some sort of redirection in some other forum but would appreciate a more explicit response. Thanks This is not legal for some reason -- is there a way im trying to just search and display results from a price drop box but it doesnt seem to work it ignores the while statement and just prints the entire database heres my code if it helps Quote <?php mysql_connect("localhost", "root") or die(mysql_error()); // makes a connection mysql_select_db("estate_agents") or die('I cannot connect to the database because: ' . mysql_error()); //conects to the database $price = $_POST['Price']; $query = "SELECT * FROM properties"; $result = mysql_query($query); switch ($price) { case '1' : $price_low = 100; $price_high = 300 ; " (I would like to pay less and get less specifications) < ".$price_low."-".$price_high.">"; break; case '2' : $price_low = 200; $price_high = 500; " (I would like to pay for what I get so what I get is equivalent to the price) < ".$price_low."-".$price_high.">"; break; case '3' : $price_low = 400; $price_high = 700; " (I would prefer to Pay as much as possible to get the best computer) < ".$price_low."-".$price_high.">"; break; case '4' : $price_low = 600; $price_high = 900 ; " (I have no preference) < ".$price_low."-".$price_high.">"; break; case '5' : $price_low = 900; $price_high = 2000 ; " (I have no preference) < ".$price_low."-".$price_high.">"; break; } //gives the different vaules for each drop down option from the input form for price ?> <table border="1" width="100%" height="10"> <tr> <td bgcolor="#FFFFFF">House Number</td> <td bgcolor="#FFFFFF">Street NamePrice</td> <td bgcolor="#FFFFFF">Area</td> <td bgcolor="#FFFFFF">Postcode</td> <td bgcolor="#FFFFFF">Type of Property</td> <td bgcolor="#FFFFFF">Number of Bedrooms</td> <td bgcolor="#FFFFFF">Number of Bathrooms</td> <td bgcolor="#FFFFFF">Price</td> <td bgcolor="#FFFFFF">Image</td> <td bgcolor="#FFFFFF">Description</td> </tr> <?php while ($row = mysql_fetch_array($result)) { if (($row['Price'] >= $price_low) && ($row['Price'] <= $price_high)) //price ?> <tr> <td align="center" bgcolor="#FFFFFF"><?php echo $row["Address_Line_1"]; ?></a></td> <!-- fetch the model name from the database and display in table --> <td align="center" bgcolor="#FFFFFF"><?php print $row["Address_Line_2"]; ?> </td> <!-- fetch the price from the database and display in the table--> <td align="center" bgcolor="#FFFFFF"><?php print $row["Area"]; ?> </td> <!-- fetch the type from the database and display in the table --> <td align="center" bgcolor="#FFFFFF"><?php print $row["Post_Code"]; ?> </td> <!-- fetch the type from the database and display in the table --> <td align="center" bgcolor="#FFFFFF"><?php print $row["Type_of_Property"]; ?> </td> <!-- fetch the size from the database and display in the table --> <td align="center" bgcolor="#FFFFFF"><?php print $row["Number_of_Bedrooms"]; ?> </td> <!-- fetch the skill from the database and display in the table --> <td align="center" bgcolor="#FFFFFF"><?php print $row["Number_of_Bathrooms"]; ?> </td> <!-- fetch the style from the database and display in the table --> <td align="center" bgcolor="#FFFFFF"><?php print $row["Price"]; ?> </td> <!-- fetch the style from the database and display in the table --> <td align="center" bgcolor="#FFFFFF"><?php print $row["Property_Image"]; ?> </td> <!-- fetch the style from the database and display in the table --> <td align="center" bgcolor="#FFFFFF"><?php print $row["Description"]; ?> </td> <!-- fetch the style from the database and display in the table --> </tr> <?php }//while ?> i am newish to php any help is much appreciated On my search result page, I wanted to search for "Nintendo DS Lite - Pink" I used following code: Ex: Code: [Select] $search_text = "Nintendo DS Lite Pink"; $kt=split(" ",$search_text);//Breaking the string to array of words // Now let us generate the sql while(list($key,$val)=each($kt)) { if($val<>" " and strlen($val) > 0) { $q .= " name like '%$val%' or "; } }// end of while //Remove the last 'OR' $q=substr($q,0,(strlen($q)-3)); Than the $q would be: Code: [Select] SELECT * FROM `products` WHERE name like '%Nintendo%' or name like '%DS%' or name like '%Lite%' or name like '%Pink%' And i am getting Mysql Output given below: 1) Activity Meter - DS. 2) Nintendo DS Red. 3) Nintendo DS Lite Pink. 4) Nintendo DS Lite Turquoise. But the third result is most accurate/relevant then first two result. Please help me out to get the most accurate row first then the relevant rows as per their relevancy with search term "$search_text" Many Thanks in Advance. After a few days of searching and running across a problem what is almost like mine on these forums (cant seem to find the link now) where the person was looking to search a database using checkboxes. What I am trying to do is use a list of checkboxes (http://www.animeseason.com/anime-list/categories/) exactly like this link and search my table which has the genres as columns. I am new to PHP and don't really have a starting point. I have taken a bunch of examples and came up with this. My HTML form with a list of all my checkboxes. Code: [Select] <form method="post" ACTION = "php/do_search.php"> <ul class="cat_col"> <li><input type="checkbox" name="cat_check[]" value="1"> <a href="#Action">Action</a></li> <li><input type="checkbox" name="cat_check[]" value="2"> <a href="#Adventure">Adventure</a></li> <li><input type="checkbox" name="cat_check[]" value="3"> <a href="#Comedy">Comedy</a></li> <li><input type="checkbox" name="cat_check[]" value="4"> <a href="#Demons">Demons</a></li> <li><input type="checkbox" name="cat_check[]" value="5"> <a href="#Drama">Drama</a></li> <li><input type="checkbox" name="cat_check[]" value="6"> <a href="#Ecchi">Ecchi</a></li> <li><input type="checkbox" name="cat_check[]" value="7"> <a href="#Fantasy">Fantasy</a></li> <li><input type="checkbox" name="cat_check[]" value="8"> <a href="#Harem">Harem</a></li> <li><input type="checkbox" name="cat_check[]" value="9"> <a href="#Horror">Horror</a></li> <li><input type="checkbox" name="cat_check[]" value="10"> <a href="#Magic">Magic</a></li> <li><input type="checkbox" name="cat_check[]" value="11"> <a href="#Martial Arts">Martial Arts</a></li> <li><input type="checkbox" name="cat_check[]" value="12"> <a href="#Mecha">Mecha</a></li> <li><input type="checkbox" name="cat_check[]" value="13"> <a href="#Music">Music</a></li> </ul> <ul class="cat_col"> <li><input type="checkbox" name="cat_check[]" value="14"> <a href="#Mystery">Mystery</a></li> <li><input type="checkbox" name="cat_check[]" value="15"> <a href="#Ninja">Ninja</a></li> <li><input type="checkbox" name="cat_check[]" value="16"> <a href="#Parody">Parody</a></li> <li><input type="checkbox" name="cat_check[]" value="17"> <a href="#Psychological">Psychological</a></li> <li><input type="checkbox" name="cat_check[]" value="18"> <a href="#Reverse Harem">Reverse Harem</a></li> <li><input type="checkbox" name="cat_check[]" value="19"> <a href="#Romance">Romance</a></li> <li><input type="checkbox" name="cat_check[]" value="20"> <a href="#Samurai">Samurai</a></li> <li><input type="checkbox" name="cat_check[]" value="21"> <a href="#School Life">School Life</a></li> <li><input type="checkbox" name="cat_check[]" value="22"> <a href="#Science Fiction">Science Fiction</a></li> <li><input type="checkbox" name="cat_check[]" value="23"> <a href="#Seinen">Seinen</a></li> <li><input type="checkbox" name="cat_check[]" value="24"> <a href="#Shoujo">Shoujo</a></li> <li><input type="checkbox" name="cat_check[]" value="25"> <a href="#Shounen">Shounen</a></li> <li><input type="checkbox" name="cat_check[]" value="26"> <a href="#Slapstick">Slapstick</a></li> </ul> <ul class="cat_col"> <li><input type="checkbox" name="cat_check[]" value="27"> <a href="#Slice of Life">Slice of Life</a></li> <li><input type="checkbox" name="cat_check[]" value="28"> <a href="#Sports">Sports</a></li> <li><input type="checkbox" name="cat_check[]" value="29"> <a href="#Supernatural">Supernatural</a></li> <li><input type="checkbox" name="cat_check[]" value="30"> <a href="#Thriller">Thriller</a></li> <li><input type="checkbox" name="cat_check[]" value="31"> <a href="#Tragedy">Tragedy</a></li> <li><input type="checkbox" name="cat_check[]" value="32"> <a href="#Vampire">Vampire</a></li> </ul> <ul class="cat_col"> <li><input type="checkbox" name="cat_check[]" value="33"> <a href="#Movie">Movie</a></li> <li><input type="checkbox" name="cat_check[]" value="34"> <a href="#OVA">OVA</a></li> <li><input type="checkbox" name="cat_check[]" value="35"> <a href="#Top Rated">Top Rated</a></li> <li><input type="checkbox" name="cat_check[]" value="36"> <a href="#Currently Airing">Currently Airing</a></li> <li><input type="checkbox" name="cat_check[]" value="37"> <a href="#Ended">Ended</a></li> <li><input type="checkbox" name="cat_check[]" value="38"> <a href="#Ongoing">Ongoing</a></li> </ul> <div id="submit_btn_pos"> <input type="submit" name="search" value="Lets Make Magic" class="submit_btn"> <> </form> My PHP script that right now seems to do nothing. Code: [Select] <?php //if we got something through $_POST if (isset($_POST['cat_check'])) { $con = mysql_connect("localhost","USERNAME","PASSWORD") or die("Connection error"); mysql_select_db("DATABASENAME")or die("database doesn't exist"); // sanitize user input $cleanData = array(); foreach($_POST['cat_check'] as $_comp) { //$cleanData = mysql_real_escape_query($_comp); } // Build query $compStr = implode("'), ('", $cleanData); $sql = "SELECT anime_name WHERE $_comp='1'"; } ?> My database has a layout of "Name of show, (every genere listed above)". Thanks for any help. 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>"; } } } ?> I'm trying to build a search function that will search all columns in a table. Here is what I've got: Code: [Select] if (isset($_POST['submitted'])) { $q = "SELECT * FROM children "; if(isset($_POST['query'])) { $q .= "WHERE "; $all = "SELECT * FROM children WHERE 1"; $r_all = mysqli_query($dbc, $all); while ($field = $r_all->fetch_field()) { // Get field headers for building query $f_name = "{$field->name} LIKE {$_POST['query']},:"; // Build query with search string $fn = explode(":",$f_name); // Need to convert $f_name to an array but this does not convert it to a single array but multiple arrays $q .= implode("OR", $fn); // Need to insert OR for the db query } // End while ($field = $r_all->fetch_field()) } // End if(isset($_POST['query'])) } // End if (isset($_POST['submitted'])) The explode function is what is not working for me. It gives me this (sam is the search string I entered into the form): Code: [Select] Array ( [0] => child_id LIKE sam, [1] => ) Array ( [0] => first_name LIKE sam, [1] => ) Array ( [0] => second_name LIKE sam, [1] => ) Array ( [0] => last_name1 LIKE sam, [1] => ) Array ( [0] => last_name2 LIKE sam, [1] => ) Array ( [0] => gender LIKE sam, [1] => ) Array ( [0] => dob LIKE sam, [1] => ) so instead of getting one array with each string being a value I get multiple arrays. Any ideas? Hi All, Just a couple of things with my site search, I am having trouble getting the search results to pickup any and all keywords. For example, if keywords for a search result are listed in the keywords column of my db as 'one, two, three' a search query for 'one two' is fine but a search for 'one three' will not display the search result. Instead of treating the keywords seperately it is treating all keywords as a whole phrase. How can I make the search results pickup any keyword regardless of order. Secondly I'm having trouble getting the search results to display by keyword relevance, any help is greatly appreciated. Thanks. Code: [Select] function search() { parent::Controller(); $this->load->model('Templating'); $this->load->model('Company'); } function index() { $this->load->view('search'); } function search_redirect() { if ($_POST['keyword'] == '') $_POST['keyword'] = 'Keyword'; redirect('search/showlist/'. urlencode(underscore($_POST['location'])).'/'. urlencode(underscore($_POST['category'])).'/'. urlencode(underscore($_POST['keyword']))); } function showlist($location = 'any', $category = 'any', $keyword = 'keyword', $offset = '0') { /* get results */ $data['companies'] = $this->Company->search($keyword, $category, $location, $offset, $name); /* paginate results */ $row = $data['companies']->row(); if($keyword == 'keyword' and $category=='any' ) { $data['categoryList'] = $this->buildCategoryList($location); } elseif(isset($row->categoryId)) { $categoryId = $row->categoryId; $data['linkList'] = $this->buildRefineList($categoryId); } $this->load->library('pagination'); $config['base_url'] = site_url().'search/showlist/'.$location.'/'.$category.'/'.$keyword.'/'; $config['total_rows'] = $this->Company->total_companies; $config['per_page'] = $this->Company->per_page; $config['num_links'] = 3; $config['uri_segment'] = $this->uri->total_segments(); $this->pagination->initialize($config); $data['pagination'] = $this->pagination->create_links(); $data['logged_in'] = $this->session->userdata('logged_in'); $data['company_id'] = $this->session->userdata('company_id'); $data['search_category'] = $category; $data['search_location'] = $location; if ($this->session->userdata('admin') != ''){ $data['admin'] = $this->session->userdata('admin'); } /* initialise template settings */ $center = 'center/list_companies'; $this->load->vars($data); $this->Templating->show($center); } Hi guys, I have a php file that will go to a site and scrape the data I need. However this site is setup to use pagination so when I try to scrape all the players names I have to do separate queries to search each page. Is there a way to find out by using code how many pages there are and query all the pages at same time? I use this code Code: [Select] <?php //first page //turn error reporting on libxml_use_internal_errors(true); //get data from this page $dom = new DOMDocument; $dom->loadHTMLFile('http://www.gametracker.com/server_info/76.73.3.42:1716/top_players/?searchipp=50#search'); $xpath = new DOMXPath($dom); // Get the total player count $rows2 = $xpath->query('//div[@class="block774"]/div'); // Get the rows from the search list $rows = $xpath->query('//table[@class="table_lst table_lst_spn"]/tr'); for ($i=1; $i<$rows->length-1; $i++) { $row = $rows->item($i); // Get the columns for a row $cols = $row->getElementsByTagName('td'); // Get the player rank (1st column) echo 'Rank:'.trim($cols->item(0)->textContent).PHP_EOL; // Get the player name (2nd column) echo 'Name:'.trim($cols->item(1)->textContent).PHP_EOL; // Get the player score (3rd column, actually 4th but number 3 is hidden) echo 'Sco '.trim($cols->item(3)->textContent).PHP_EOL; echo "<br />"; } ?> <?php //secondpage //turn error reporting on libxml_use_internal_errors(true); //get data from this page $dom = new DOMDocument; $dom->loadHTMLFile('http://www.gametracker.com/server_info/76.73.3.42:1716/top_players/?searchipp=50&searchpge=2#search'); $xpath = new DOMXPath($dom); // Get the rows from the search list $rows = $xpath->query('//table[@class="table_lst table_lst_spn"]/tr'); for ($i=1; $i<$rows->length-1; $i++) { $row = $rows->item($i); // Get the columns for a row $cols = $row->getElementsByTagName('td'); // Get the player rank (1st column) echo 'Rank:'.trim($cols->item(0)->textContent).PHP_EOL; // Get the player name (2nd column) echo 'Name:'.trim($cols->item(1)->textContent).PHP_EOL; // Get the player score (3rd column) echo 'Sco '.trim($cols->item(3)->textContent).PHP_EOL; echo "<br />"; } ?> I also have to go to that website first to see how many pages there are so I can have enough queries. hi all, in mysql, how can i extract 100 words before and 100 words after my search key? example: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla est nibh, mattis eu mattis id, pulvinar eu augue. Duis ut sem nisi. Sed id ante sed orci vestibulum lacinia ac id nibh. Donec cursus, elit eget auctor semper, ipsum eros laoreet quam, nec ullamcorper" vestibulum is my search key Hi, I'm having two issues with my Search engine for my website. It is created to search through my database (it doesn't crawl through pages). The first problem I'm having is when I type in for example: Super Mario Bros and there is a row in my table with a field called Super Mario Brothers this row is not included as a successful result to the search. I need to somehow modify my code to search every word in every table cell in the database. So another example. I have 5 rows, each with one cell, named as follows: One Two Three Four Five If I was to type in the search box: One Two Three Four Five it should display all rows (it obviously doesn't do that right now lol) The second issue has to do with my sql query. It looks like this: $query = "select * from sheets where artist like \"%$trimmed%\" OR title like \"%$trimmed%\" order by artist"; $numresults=mysql_query($query); I need this query to search in the columns artist and title (like it is doing above) AS WELL as search only those rows that have an active status set to 'yes'. I tried to type something like: $query = "select * from sheets where active='yes' && artist like \"%$trimmed%\" OR title like \"%$trimmed%\" order by artist"; but this obviously causes problems. How do i require the query to include rows that are active, but have it look through artist OR title as well? Here is my code below. Any insight appreciated. Will be working on it til someone is available. Thanks <?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; // 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 artist like \"%$trimmed%\" OR title like \"%$trimmed%\" order by artist"; $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); // If we have no results if ($numrows == 0) { // 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, however, 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: #f5f5f5;'><a href='request.php'>Request A Sheet Here</a></td></tr>"; } // 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 = ""; } ?> <br /><div id='headsearch'></div> <div style="width: 210px; 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='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(($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>"; ?> Hello, I have a search engine on my website that uses the following code: Code: [Select] //SQL FOR *SEARCH.PHP $table = "videos"; $search = $_GET['q']; // explode search words into an array $arraySearch = explode(" ", $_GET['q']); // table fields to search $arrayFields = array(0 => "title", 1 => "titletext", 2 => "tags", 3 => "originaltitle", 4 => "url"); $countSearch = count($arraySearch); $a = 0; $b = 0; $sql = "SELECT * FROM ".$table." WHERE status ='1' AND ("; $countFields = count($arrayFields); while ($a < $countFields) { while ($b < $countSearch) { $sql = $sql."$arrayFields[$a] LIKE '%$arraySearch[$b]%'"; $b++; if ($b < $countSearch) { $sql = $sql." AND "; } } $b = 0; $a++; if ($a < $countFields) { $sql = $sql.") OR ("; } } $sql = $sql.") ORDER BY (videos.up-videos.down) DESC LIMIT $start, $limit"; $result = mysql_query($sql); My problem is that the SQL Query includes even videos that have STATUS='0' .. I only want the STATUS='1' to be shown.. How come? Thanks for help Hi guys and girls, I am having trouble finding out wether the query made no matches rather than just displaying the matches. So what I would want is for the search term to look at the database, and if there's not matches then say, "No match for your search term" Code: [Select] function search_applications() { global $dbc; echo '<form method="post" action="" id="search">'. "\n"; echo '<label for="search_applications">Search for an application</label>'. "\n"; echo '<input type="text" name="search_applications" />'. "\n"; echo '<input type="submit" name="submit" />'. "\n"; echo '</form>'. "\n"; if(isset($_POST['submit'])){ $search_applications = $_POST['search_applications']; if ($search_applications == "") { echo "<p>You forgot to enter a search term"; } //if (preg_match("/\b$search_applications\b/i")){ if(preg_match("/^[ a-zA-Z]+/", $search_applications)){ //for testing the variables //echo $search_applications; $sql="SELECT title, category, content FROM distributors_content WHERE title LIKE '%" . $search_applications . "%' OR category LIKE '%" . $search_applications ."%' OR content LIKE '%" . $search_applications ."%'"; $result=mysqli_query($dbc, $sql); //-create while loop and loop through result set while($row=mysqli_fetch_array($result)){ $title =$row['title']; $category=$row['category']; $content=$row['content']; //-display the result of the array echo "<ul>\n"; echo '<li> <a href="index.php?article='.$row['title'].'&&page=application" title=""> '.$title . ' ' . $category . '</a></li>'."\n"; echo "</ul>"; } }else{ echo "<p>Enter another search term</p>"; } } } Any pointers would be good Thank you Hi, I'm very new to PHP and have been working on a small project that is a search engine connected to a mysql database. I can't seem to display the results from the search across multiple pages, when I click the Next button it just brings me to a blank page with no content except for my search form on top. I have a feeling that my problem lies in how I'm passing variables from one page to another as I realize that the URL of page 2 doesn't have the users search anymore. What do I need to change to get multiple pages working? Code: [Select] <?php if(isset($_GET['submit'])){ if(isset($_GET['name'])){ if(preg_match("/^[ a-zA-Z0-9]+/", $_GET['name'])){ $name=$_GET['name']; // Connect to database $db=mysql_connect("localhost", "root", "1234") or die ('Cannot connect: ' . mysql_error()); // Select database $mydb=mysql_select_db("mydb"); // Check page num, if no page num set to 1 if(isset($_GET['pagenum'])){ $pagenum = $_GET['pagenum']; } else{ $pagenum = 1; } // Query the database table $sql="SELECT id, ProductName, Price FROM testdb WHERE ProductName LIKE '%" . $name ."%'"; // Run query $result=mysql_query($sql); // Check to see if any results were found, if not, tell user $resultnum = mysql_num_rows($result); // Number of results per page $page_rows = 4; // Page number of previous page $last = ceil($resultnum/$page_rows); // Make sure page number isn't below 1 or above maximum if($pagenum < 1){ $pagenum = 1; } elseif($pagenum > $last){ $pagenum = $last; } // Set range to display in query $max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows; $sql2 = "SELECT id, ProductName, Price FROM testdb WHERE ProductName LIKE '%" . $name ."%' $max"; $data_p = mysql_query($sql2); if($resultnum == 0){ echo "<p class='p1'>No results found for query: " . $name . "</p>"; } else{ echo "<table class='sortable'>"; echo "<thead>"; echo "<tr>"; echo "<th>" . "Model Number" . "</th>"; echo "<th>" . "Product" . "</th>"; echo "<th>" . "Price" . "</th>"; echo "</tr>"; echo "</thead>"; // Loop through results $bg = '#9D9D9D'; while($row=mysql_fetch_array($data_p)){ $bg = ($bg=='#9D9D9D' ? '#C7C7C7' : '#9D9D9D'); $ProductName=$row['ProductName']; $Price=$row['Price']; $ID=$row['id']; // Display results of array echo "<tr bgcolor='" .$bg . "'>"; echo "<td width='30%', align='center'>" . " " . "</td>"; echo "<td width='60%', align='center'>" . "<a href=\"search.php?id=$ID\">" . $ProductName . "</a></td>"; echo "<td width='10%', align='center'>" . $Price . "</td>\n"; echo "</tr>"; echo "<tr><td></td></tr>"; } echo "</table>"; echo "<p>"; echo " --Page $pagenum of $last-- </p>"; if($pagenum == 1){ } else{ echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> "; echo " "; $previous = $pagenum-1; echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> "; } if ($pagenum == $last){ } else{ $next = $pagenum+1; echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> "; echo " "; echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> "; } } } else{ echo "<p class='p2'>Please enter a query.</p>"; } } } ?> The search form looks like this... Code: [Select] <form method="get" action="search.php" id="searchform"> <input type="text" name="name" size = "42"> <input type="submit" name="submit" value="Search" STYLE="font-family: Arial, Helvetica, sans-serif; font-weight: bold;"> </form> Thanks. I want to have a search product feature, but I would like members to be able to search multiple fields in one go i.e. product_code, Product_name in one MySQL query. The thing is, members have to be logged on, so the query must also only show results relating to that specific member, via the session[member_ID], my current query for listing products for that specific member is : Code: [Select] $sql = "SELECT productId, productCode, image, name, price, stock_level FROM product_inventory WHERE memberr_ID = '" . $_SESSION['SESS_mem_ID'] . "; How would I change the above into a search query to search for productcode, productname and still only show results beloging to this member using the session data ? all help appreciated I'm hoping this is a simple question. When I use the code below, my twitter search query appears in BOLD within the returned results. I would like to style the search term differently. I can use CSS to style the avatar, author, and other information within the returned results etc, but I can't figure out how to style the search term ($q) within the returned twitter information. Any help would be much appreciated. <?php class twitter_class { function twitter_class() { $this->realNamePattern = '/\((.*?)\)/'; $this->searchURL = 'http://search.twitter.com/search.atom?lang=en&q='; $this->intervalNames = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year'); $this->intervalSeconds = array( 1, 60, 3600, 86400, 604800, 2630880, 31570560); $this->badWords = array('somebadword', 'anotherbadword'); } function getTweets($q, $limit=15) { $output = ''; // get the search result $ch= curl_init($this->searchURL . urlencode($q)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); $response = curl_exec($ch); if ($response !== FALSE) { $xml = simplexml_load_string($response); $output = ''; $tweets = 0; for($i=0; $i<count($xml->entry); $i++) { $crtEntry = $xml->entry[$i]; $account = $crtEntry->author->uri; $image = $crtEntry->link[1]->attributes()->href; $tweet = $crtEntry->content; // skip tweets containing banned words $foundBadWord = false; foreach ($this->badWords as $badWord) { if(stristr($tweet, $badWord) !== FALSE) { $foundBadWord = true; break; } } $tweet = str_replace('<a href=', '<a target="_blank" href=', $tweet); // skip this tweet containing a banned word if ($foundBadWord) continue; // don't process any more tweets if at the limit if ($tweets==$limit) break; $tweets++; // name is in this format "acountname (Real Name)" preg_match($this->realNamePattern, $crtEntry->author->name, $matches); $name = $matches[1]; // get the time passed between now and the time of tweet, don't allow for negative // (future) values that may have occured if server time is wrong $time = 'just now'; $secondsPassed = time() - strtotime($crtEntry->published); if ($secondsPassed>0) { // see what interval are we in for($j = count($this->intervalSeconds)-1; ($j >= 0); $j--) { $crtIntervalName = $this->intervalNames[$j]; $crtInterval = $this->intervalSeconds[$j]; if ($secondsPassed >= $crtInterval) { $value = floor($secondsPassed / $crtInterval); if ($value > 1) $crtIntervalName .= 's'; $time = $value . ' ' . $crtIntervalName . ' ago'; break; } } } $output .= ' <div class="tweet"> <div class="avatar"> <a href="' . $account . '" target="_blank"><img src="' . $image .'"></a> </div> <div class="message"> <span class="author"><a href="' . $account . '" target="_blank">' . $name . '</a></span>: ' . $tweet . '<span class="time"> - ' . $time . '</span> </div> </div>'; } } else $output = '<div class="tweet"><span class="error">' . curl_error($ch) . '</span></div>'; curl_close($ch); return $output; } } ?> The HTML I have been using with this code is here 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> <title>Twitter</title> </head> <body> <?php require('twitter.class.php'); $twitter = new twitter_class(); echo $twitter->getTweets('example search term', 10); ?> </body> </html> This is not my code. It is from a tutorial that can be accessed from here >> http://www.richnetapps.com/php-twitter-search-parser/ This is what I was using for including an url with parameter <?php if ($fh = fopen('http://www.domain.com/search.php?query=test', 'r') ) { fpassthru($fh); fclose($fh); } ?> It's not working anymore after the hosting company did an upgrade. By the way. Alle scripts are accessible locally. What is my alternative?? Say a user puts in a support request, and for every request it generates a unqiue string, and enters it into the database. Ok, now say there is a text field, when the user enters their unique string and it finds a match, it displays the data along with it. How can I accomplish this? Im kind of new to mysql, but I know basic SQL. Would be great if somebody could point me in the right direction! Thanks |