PHP - Help Building Query For Search Function
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? Similar TutorialsHello, I would like to build a php search engine against a mysql database. I am looking for a tutorial but haven't been able to find any good ones. Any ideas of where I can find one? I need one where I can search with several words and if it has the stemmer.class.inc and so on would be great also. thanks, df Here's my build a querty code... Code: [Select] $sql = "UPDATE $tablename SET DIST_PART_NUM = '$dist_part_num', DIST_PUB = '$dist_pub', MFR_PART_NUM = '$mfr_part_num', MFR_PUB = '$mfr_pub', ITEM_DESC = '$item_desc', ITEM_STD_DESC = '$item_std_desc', ITEM_COPY = '$item_copy', COST = '$cost', GP_MULT = '$gp_mult', ITEM_IMAGE = '$item_image', ITEM_URL = '$item_url', COUNTRY_OF_ORIG = '$country_of_orig', CATEGORY_ID = '$category_id', PICGROUP_KEY = '$picgroup_key', UPC_CODE = '$upc_code', LEADTIME = '$leadtime', UNITS = '$units', LENGTH = '$length', WIDTH = '$width', HEIGHT = '$height', WEIGHT = '$weight', FLAG_HAZARDOUS = '$flag_haz', FLAG_LTL = '$flag_ltl', FLAG_NON_RETURNABLE = '$flag_non', CAMPAIGN_KEY = '$campaign_key', "; foreach($atr as $key => $value) { $sql .= $value . "='" . addslashes($_POST[$value]) . "',"; } $sql2 = rtrim($sql,","); $sql2 .= " WHERE DIST_PART_NUM = '$partnumber' OR MFR_PART_NUM = '$partnumber'"; Now the query get's built 100% fine that's not the issue... my issue is that sine if the table fields are named something like #_of_shelves... and the # sign causes a MySQL error... You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 26 How can i allow for the # sign, or any other character that can cause issues like () . , * ~ etc.... i tried encompassing the field name with single quotes 'fieldname' and with those slanted ones `tablename` but that did not help. Any ideas? Thanks! Hi, I had a form which contains, 8 select boxes. In those 8 select boxes, 3 of the boxes are interlinked, like, I am able to generate data in other 2 select boxes, if one box is been selected. i.e. based upon selection of one select box, and i am able to generate data in other select box. So, 3 select boxes are interlinked. And remaining 5 selects are optional, if the user selects, then we need to generate data based upon selection of the user. Here the main issue is how to grab data in the post back form, like, how to capture the number of selects boxes selected and what are those selected, and based upon that we need to generate data. Here one more important thing is that, in the report generation form(postback form), I need to show the data in a table. So , in table I had 9 columns and these would be common to whatever the selection made, but, only the requeired data would be changed based upon the selection of the remaining 5 optional boxes. Hope you got me!!!! Hi, I have been trying to improve my PHP programming skills by following the Lynda.com Beyond the basics tutorial and they came to a section where they were building common database methods inside a database class. Since they did not have PHP 5.3 (Where late static bindings is introduced) they had to place code referring to self:: inside of each class that needs this functionality. It seems that not having late static binding was binding self to the database class and not to other classes that call it statically. I will insert some code to explain this better. Long story short, I was really interesting in getting an attributes function working and as I do not have late static bindg either, I cannot figure out how to call it from inside a class to make it function correctly. Here is some code. Below is the attribute class they wrote. Each class declared an array of attributes for each of the classes that want to call this method like protected static $db_fields = array('id', 'email', 'password', 'etc'); Code: [Select] protected function attributes() { // return an array of attribute names and their values $attributes = array(); foreach(self::$db_fields as $field) { if(property_exists($this, $field)) { $attributes[$field] = $this->$field; } } return $attributes; } They planned on moving this code to a DatabaseObject class after they get LSB but until then, have to include it in every class that wants use this. Is there any way to write this as a function, include it in a class, and call the method without late static binding.. or even place this inside a database class and call it from another class without LSB? Forgive me if I am not explaining this correctly, again, I am still learning. My version of PHP is 5.2.6. I am trying to write a more elegant solution to be able to check an object, find only the properties in an object that have values, and update those values in a database with a matching ID. I am extending a class from a generic user class here is an example of my code Code: [Select] <?php require_once('User.php'); require_once('Database.php'); class Vendor extends User { protected static $vendor_attributes = array('id', 'nothing' , 'tagline' , 'bio'); protected static $table_name = "user_vendors"; public $tagline; }//close class ?> 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 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! Hi 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, 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? 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 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. 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. 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 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>"; } } } ?> 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); } I've followed the PHP Freaks pagination tutorial which you can find here. And I also got it to work, the only problem is that the script won't work when I use the query outside of the function. Here's the function: <?php function knuffix_list ($query, $dbc) { // find out how many rows are in the table: $query_row = "SELECT COUNT(*) FROM con"; $query_run = mysqli_query ($dbc, $query_row); $row = mysqli_fetch_row($query_run); $num_rows = $row[0]; // number of rows to show per page $rows_per_page = 5; // find total pages -> ceil for rounding up $total_pages = ceil($num_rows / $rows_per_page); // get the current page or set a default if (isset($_GET['current_page']) && is_numeric($_GET['current_page'])) { // make it an INT if it isn't $current_page = (int) $_GET['current_page']; } else { // default page number $current_page = 1; } // if current page is greater than total pages then set current page to last page if ($current_page > $total_pages) { $current_page = $total_pages; } // if current page is less than first page then set current page to first page if ($current_page < 1) { $current_page = 1; } // the offset of the list, based on current page $offset = (($current_page - 1) * $rows_per_page); echo "test " . $query; // SCRIPT ONLY WORKS IF I INSERT QUERY HERE $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id ORDER BY contributed_date DESC LIMIT $offset, $rows_per_page"; $data = mysqli_query ($dbc, $query) or die (mysqli_error ($dbc)); // Loop through the array of data while ($row = mysqli_fetch_array ($data)) { global $array; // Variables for the table $con_id = $row['con_id']; $likes_count = $row['likes']; $dislikes_count = $row['dislikes']; $dbuser_name = $row['nickname']; $dbuser_avatar = $row['avatar']; $user_id = $row['user_id']; // The TABLE echo "<table padding='0' margin='0' class='knuffixTable'>"; echo "<tr><td width='65px' height='64px' class='avatar_bg' rowspan='2' colpan='2'><img src='avatar/$dbuser_avatar' alt='avatar' /></td>"; echo "<td class='knuffix_username'><strong><a href='profile.php?user=$dbuser_name' title='Profile of $dbuser_name'>" . $dbuser_name . "</a> ___ " . $user_id . "____ <form action='' method='POST'><button type='submit' name='favorite' value='fav'>Favorite</button></form>"; echo "</strong><br />" . $row['category'] . " | " . date('M d, Y', strtotime($row['contributed_date'])) . "</td></tr><tr><td>"; echo "<form action='' method='post'> <button class='LikeButton' type='submit' name='likes' value='+1'>Likes</button> <button class='DislikeButton' type='submit' name='dislikes' value='-1'>Dislikes</button> <input type='hidden' name='hidden_con_id' value='" . $con_id . "' /> </form></td><td class='votes'>Y[" . $likes_count . "] | N[" . $dislikes_count . "]</td></tr>"; echo "<tr><td class='knuffix_name' colspan='3'><strong>" . htmlentities($row['name']) . "</strong><br /></td></tr>"; echo "<tr><td colspan='2' class='knuffix_contribution'><pre>" . $row['contribution'] . "</pre><br /></td></tr>"; echo "</table>"; // POST BUTTONS inside the table $likes = $_POST['likes']; $dislikes = $_POST['dislikes']; $con_id = $_POST['hidden_con_id']; $favorite = $_POST['favorite']; $array = array ($likes, $dislikes, $con_id, $user_id, $favorite); } /********* build the pagination links *********/ // BACKWARD // if not on page 1, show back links and show << link to go back to the very first page if ($current_page > 1) { echo " <a href='{$_SERVER['PHP_SELF']}?current_page=1'><<</a> "; // get previous page number and show < link to go to previous $prev_page = $current_page - 1; echo " <a href='{$_SERVER['PHP_SELF']}?current_page=$prev_page'><</a> "; } // CURRENT // range of number of links to show $range = 3; // loop to show links in the range of pages around current page for ($x = ($current_page - $range); $x < (($current_page + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $total_pages)) { // if we're on current page if ($x == $current_page) { // highlight it but don't make a link out of it echo "[<b>$x</b>]"; // if it's not the current page then make it a link } else { echo "<a href='{$_SERVER['PHP_SELF']}?current_page=$x'>$x</a>"; } } } // FORWARD // if not on the last page, show forward and last page links if ($current_page != $total_pages) { // get next page $next_page = $current_page + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?current_page=$next_page'>></a> "; // echo forward link for last page echo " <a href='{$_SERVER['PHP_SELF']}?current_page=$total_pages'>>></a> "; } /***** end building pagination links ****/ mysqli_close($dbc); } ?> As you can see above, the script will only work if I put the query right below the $offset variable and above the $data variable. I put the test echo above the query to see how the query looks like when I induce the query from the outside through the function parenthesis into the function, and this is what I get printed out: test SELECT * FROM con, user WHERE con.user_id = user.user_id ORDER BY contributed_date DESC LIMIT , Obviously the $offset and the $rows_per_page variables are not set, when I induce the query from the outside into the function. So in that sense my question is: How can I induce the query from the outside into the function SO THAT the $offset and the $rows_per_page variables are set as well and NOT empty? p.s. I need the query outside of the function because I'm using a sort by category functionality. 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 |