PHP - [php] Search Class Problem
Hey guys im just starting to use Prepared Statements in php and i am trying to build a search but i have come across a problem. Hope someone can help or point me to more information on how to resolves this.
Ok here is the code below:: public function search($string) { if(strlen($string) > 40) { return "Woow too many words, please shorten your search."; } if(empty($string)) { return "I'm a search, you type things in and I find. Please enter something and try again!"; } if(strlen($string) <= 3) { return "Come on dude, you expect me to find summin with that? Type some more tags in!"; } $x=0; // Teh string could be multiple searches so explode:: $string = explode(" ", $string); foreach($string as $search) { $x++; if($x == 1) { @$sql .= "(blog_tags LIKE '%$search%')"; } else { @$sql .= " OR (blog_tags LIKE '%$search%')"; } } $sql = "SELECT blog_tags FROM subarc_blog WHERE $sql LIMIT 40"; // TODO:: Count how many search results found:: $stmt = $this->conn->prepare($sql); $stmt->execute(); $stmt->bind_result($search); Ok by using the bind_result() i need to know how many result are being returned to add them to a variable is this correct ? if so how can i tell how many results have been returned ? hope this makes sense Similar TutorialsHey guys! I have spent the last 5 and a half hours banging my head up against the wall trying to fix this to no avail so I guess its time to ask the experts!!! I am having a problem with my membership class. Basically, it works perfectly if a user logs in using sessions and not cookies. But when remember is set to 1 (they ticked the remember me checkbox), the mysql query fails on this line when we run $member_class->member_class(); Code: [Select] $result = mysql_fetch_array(mysql_query("SELECT * FROM members WHERE email = '{$email}' AND token ='{$token}' AND ip_address LIKE '{$ip_address}%'"), MYSQL_ASSOC) or DIE ($this->query_error); Everything matches up except for the $token value. Basicly I believe that a new token is updated in the mysql database, before the token value in the cookie is updated as when I print $token, it definitly matches up with the token value in the mysql database. But from reading through the code, it all looks perfectly fine to me which is why i am so confused. If i change $newtoken = $this->token(); // generate a new token to $newtoken = '1234'; the script also works perfectly fine without errors (though not very secure so would like the token to change values! Really appreciate any input! Cheers <?php // member class // handlers member logon class member_class { var $message = ''; var $query_error = 'ERROR: something went wrong when accessing the database. Please consult your webmaster'; function member_class() { //constructor if (!$_SESSION['member_id']) { //fills session with empty values $this->set_session_defaults();; } if ($_SESSION['logged_in']) { //already logged in $this->check_session(); } if ($_COOKIE['remember']) { $this->check_remembered($_COOKIE['remember']); } } function check_login($email,$password,$remember,$redirect) { $email = mysql_escape_string($email); $salt='s+(_v'; $password = mysql_escape_string(hash('sha512', $salt . $password)); $result=mysql_fetch_array(mysql_query("SELECT * FROM members WHERE email = '{$email}' AND password = '{$password}'"), MYSQL_ASSOC); if ($result) { $this->set_session($result,$remember,true); return true; } else { $this->failed = true; $this->logout(); //create error message telling user that either the email address does not exist, or they have entered the wrong password associated with the email address $result=mysql_fetch_array(mysql_query("SELECT email FROM members WHERE email = '{$email}'")); if($result) { $this->message .= 'Incorrect Password. Please try again'; } else { $this->message .= 'The email address '.$email.' does not exist. Please try again or <a href="/register.php" class=" cboxElement">create a new account</a>.'; } return false; } } function logout() { // blowup cookie setcookie('remember',time()-3600); $this->set_session_defaults(); } function set_session($result,$remember,$init = true) { $member_id=$result['member_id']; if ($init) { $session = mysql_escape_string(session_id()); $ip_address = mysql_escape_string($_SERVER['REMOTE_ADDR']); $newtoken = $this->token(); // generate a new token // generate a random token $update = mysql_query("UPDATE members SET session='{$session}', token='{$newtoken}', ip_address='{$ip_address}' WHERE member_id='{$member_id}'") or DIE ($this->query_error); } $_SESSION['member_id'] = $result['member_id']; $_SESSION['email'] = htmlspecialchars($result['email']); $_SESSION['fullname'] = $result['fullname']; $_SESSION['token'] = $newtoken; $_SESSION['logged_in'] = true; if ($remember) { $this->update_cookie($newtoken); } } function update_cookie($token) { $cookie = serialize(array($_SESSION['email'],$token)); //print $token; setcookie('remember',$cookie, time()+12099600); } function check_remembered($cookie) { $serializedArray=$cookie; $serializedArray = stripslashes($serializedArray); list($email,$token) = unserialize($serializedArray); if(empty($email) or empty($token)) { return; } else { $email = mysql_escape_string($email); $token = mysql_escape_string($token); $ip_address = mysql_escape_string($_SERVER['REMOTE_ADDR']); //changed from = '{ip_address} to like '{ipaddress}% so we are not strict in ip address we only limit to first 3 charactors of ip $ip_address = substr($ip_address, 0, 3); $query = "SELECT * FROM members WHERE email = '{$email}' AND token ='{$token}' AND ip_address LIKE '{$ip_address}%'"; print $query; $result = mysql_fetch_array(mysql_query("SELECT * FROM members WHERE email = '{$email}' AND token ='{$token}' AND ip_address LIKE '{$ip_address}%'"), MYSQL_ASSOC) or DIE ($this->query_error); if (!$result) { // $this->set_session($result,false,false); }else{ $this->set_session($result,true,true); } } } function token() { // generate a random token for($i=1;$i<33;$i++) { $seed .= chr(rand(0,255)); } return md5($seed); } function check_session() { $email = mysql_escape_string($_SESSION['email']); $token = mysql_escape_string($_SESSION['token']); $session = mysql_escape_string(session_id()); //if ip address changes it will fail POSSIBLY DO NOT NEED THIS! $ip_address = mysql_escape_string($_SERVER['REMOTE_ADDR']); //check only the first 4 charactors of ip address incase user changes ip in corporate workplace etc ALSO CHANGED = TO LIKE IN MYSQL QUERY AND ADDEED % TO THE END AS WILDCARD $ip_address = substr($ip_address, 0, 3); $result = mysql_fetch_array(mysql_query("SELECT * FROM members WHERE email='{$email}' AND token='{$token}' AND session='{$session}' AND ip_address LIKE '{$ip_address}%'"), MYSQL_ASSOC or DIE ($this->query_error)); if ($result != false){ }else{ $this->logout(); } } }?> Hi, this php code not working for some reason Code: [Select] class db { public function connect() { $yhteys = new PDO("mysql:host=*****;dbname=*****", "*******", "******"); } public function get($query, $parameters){ $prepare = $yhteys->prepare($query); $prepare->execute($parameters); $result = $prepare->fetch(); $count = $prepare->rowCount(); return array($result, $count); } } Code: [Select] $db = new db(); $content = $db->get("SELECT * FROM tuotteet WHERE id = ?", array("1")); print $content; It gives error:Parse error: syntax error, unexpected T_OBJECT_OPERATOR Thank you for help! class Z { function foo() { // do somethig } } class X { $x function __contruct() { $this->x = new z(); } function var() { $this->x->foo(); // Fatal error: Using $this when not in object contex } } // Class declaration here class Y { function __contruct() { $z = new z(); $x = new x(); } } Hi im having trouble getting the below code to listen to my css margin settings. Just to clear up the server side of things, can anybody tell me wether or not im using the correct syntax in the code below? Code: [Select] else { echo("<p class=\"passed\">Thankyou for submiting your details, you will be added to our directory shortly</p>"); }} I have the code as given below: <?php class ABC { function printValue() { print("This value shall be printed" . $this->x); } } class BCD extends ABC { private $x=10; } $bcd=new BCD; $bcd->printValue(); ?> But when I try to access printValue function from the paren class it gives me error... Fatal error: Cannot access private property BCD::$x in /var/www/html/trainingweb/modules/test/TestAtitProblem.php on line 5 As the public method of ABC would be extended to BCD, it shall have access to its own member. please help... So... I have the following code for my rss_reader class: <?php class rss_reader { const USE_CURL = TRUE; private $_userAgent = ''; private $_url = ''; public function __construct($url, $userAgent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1') { $this->_url = $url; $this->_userAgent = $userAgent; } public function writePOST() { $postval= $this->getPOST(); echo $postval; } public function getPOST($format = '<b>%s</b>%s<i>%s</i>') { $xml = $this->getXML(); $script1 = $xml->channel->item->title; $script2 = $xml->channel->item->description; $script3 = $xml->channel->item->pubDate; return sprintf($format, $script1, $script2, $script3); } private function getXML() { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT, $this->_userAgent); curl_setopt($ch, CURLOPT_TIMEOUT ,3); $data = curl_exec($ch); curl_close($ch); return new SimpleXMLElement($data); } } Basically, atm it writes the newest post found at the RSS feed. What I wan't to do is extend this to create an array of all of the posts that I can iterate over to "write" ALL of the posts. I will then later work on a method for pagination. Atm though, I am kinda lost and don't really know where to start. Anyone know how I could accomplish this? thanks much. ps: everything else with the rss reader works as intended. Well i have this set of codes <?php include "includes/config.php"; class template{ var $page; var $built; public $block = array(); function _start($tpl){ $this->page = $tpl; } function set_array($data){ $this->block[] = $data; } function _show(){ foreach($this->block as $k => $v){ foreach($v as $k1 => $v1){ //echo $k1."<br />"; //echo $v1."<br />"; $this->page = str_replace("{".$k1."}", $v1, $this->page); } } echo $this->page; } } $template = new template(); $file = "<html> <body> <p>{CAT}</p> <p>{SUBCAT}</p> </body> </html>"; $template->_start($file); // Category Query while($row1 = mysql_fetch_assoc($cat)){ $template->set_array(array("CAT" => $row1['title'])); // Sub Category Query while($row2 = mysql_fetch_assoc($subcat)){ $template->set_array(array("SUBCAT" => $row2['title'])); } } $template->_show(); ?> Now, when i echo $k1 or $v1 they display the keys and values in the correct order like CAT1 SUBCAT1.1 SUBCAT1.2 CAT2 SUBCAT2.1 SUBCAT2.2 but when it goes through the str_replace its only displays the CAT1 and SUBCAT1.2 what going wrong? I got some help from this forum previously and am having some more issues. I created a database class that works and returns a PDO object. I am having trouble figuring out how to use the object in another class I want to use to access some CRUD functions. I get to the point where I start using the pdo object I create in the database class and my code fails. I am obviously calling the pdo object property incorrectly. I guess I don't understand the proper syntax. I've included the code for the database class and the CRUD class. The problem starts at the point where I try to run a prepared statement. I have include a comment "Problem stars here" to indicate that point. There is a lot of debug stuff still in the code. Thanks, --Kenoli <?php class Db { public $pdo = ''; public $message = 'A message from db!<br><br>'; function __construct() { $servername = "localhost"; $username = "root"; $password = ""; $dbname = "tio-local"; $db_options = array( PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ); try { $this->pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password, $db_options); // set the PDO error mode to exception $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } // End Try catch(PDOException $e) { echo "Error: " . $e->getMessage(); } } // End __construct } // End class definition DB.php $db = new Db; $pdo = $db->pdo; print_r ($pdo); ?> <?php // Db_functions.php include_once ('Db.php'); // $db instantiated in class file $pdo = $db->pdo; class Db_functions { public $pdo = ''; function __construct($pdo) { $this->pdo = $pdo; } // Close __construct public function insert($table_name, $white_list, $insert_array) { if ($white_list == '' && $table_name == 'Sites') { $white_list = array('gone'=>'','site_name' =>'', 'site_address' =>'', 'grommets' =>'', 'tape' =>'', 'site_image' =>'', 'description' =>'', 'surface' =>'', 'tio_contact' =>'', 'site_contact' =>'','owner' =>'', 'lessee' =>'', 'contact_phone' =>'', 'contact_email' =>'', 'contact_date' =>'', 'comments' =>''); } elseif ($white_list == '' && $table_name == 'Persons') { $white_list = array('gone'=>'', 'fname'=>'', 'lname'=>'', 'tio'=>'', 'volunteer'=>'', 'general'=>'', 'artist_pic'=>'', 'email'=>'', 'website'=>'', 'telephone'=>'', 'address'=>'', 'city'=>'', 'state'=>'', 'zip'=>'', 'statement'=>''); } echo '<strong>***The following is the PDO object: </strong>'; print_r ($this->pdo); echo '<p>The following is the $white_list:<br>'; echo '<pre>'; print_r ($white_list); echo '</pre>'; echo '<strong>***The following is the PDO object: </strong>'; print_r ($this->pdo); /** Test and remove any unpermitted columns **/ $insert_array = array_intersect_key($insert_array, $white_list); echo '<strong>***The following is the PDO object: </strong>'; print_r ($this->pdo); /** Generate variables to create prepared statements **/ foreach($insert_array as $key => $value) { $col .= $key . ', '; $val .= ':' .$key . ', '; } echo '$col = ' . $col . '<p>'; echo '$val = ' . $val . '<p>'; echo '<strong>***The following is the PDO object: </strong>'; print_r ($this->pdo); /** Remove ', ' at end of arrays and create prepared statement */ $col = substr_replace($col ,"",-2); $val = substr_replace($val ,"",-2); $sql = "INSERT INTO Sites ($col) VALUES ($val)"; echo "<p>SQL = $sql<br><br>"; /** Debug **/ echo '<h3>More</h3<br>'; /** Register prepared statement */ /****** PROBLEM STARTS HERE *****/ $stmt = $this->pdo->prepare($sql); echo '<h3>More2</h3>'; /** Create [:field, $value] pairs. */ foreach($insert_array as $key => $value) { $param = ':' . $key; $stmt->bindParam($param, $$value); //} /** Create [field => value] array */ foreach($insert_array as $key => $value) { $insert[$key] = $value; } /** Execute statement using $insert array. **/ $stmt->execute($insert); } // End insert function } // Close class definition $db_functions = new Db_functions($pdo); $insert_array = array('fname' => 'John', 'lname' => 'Hancock'); $db_functions->insert('Persons', '', $insert_array); echo '<pre>'; print_r ($db_functions); echo '</pre>'; ?> Edited February 6 by kenoli this code doesn't work, why? define("DIR", "../../"); final class MyClass { private static $PATH = DIR . '../directory/'; } hey guys i have a script ive made which loads classes automatically when called...the script works fine but when i extend the class Autoloader_Exception and it comes back with the error Code: [Select] Fatal error: Class 'Autoloader_Exception' not found in C:\www\library\autoloader.class.php on line 3 i might be missing something here but i dont know why the autoloader doesnt load the extended class if someone can please help me how i can extend the class please thanks Code: [Select] <?php class Autoloader extends Autoloader_Exception { protected static $_declared_classes = array(); public static function load_class($class_name) { $class_name = ucwords($class_name); $file = self::get_class_path($class_name); try { if (!class_exists($class_name, FALSE)) { if (file_exists($file)) { require_once $file; self::$_declared_classes[] = $class_name; } else { throw new Exception(sprintf("Class '%s' not found.<br />\n", $class_name)); } } } catch (Exception $e) { echo $e->getMessage(); } } protected static function get_class_path($class_name) { global $classes; if (array_key_exists($class_name, $classes)) { return ROOT . DS . $classes[$class_name]; } } public static function declared_classes() { echo "<pre>"; print_r(self::$_declared_classes); echo "</pre>"; } } spl_autoload_register(array('Autoloader', 'load_class')); ?> Hi, Can I know how to resolve this problem? Notice: Undefined variable: x in C:\wamp\www\i-document\search.php on line 39 Notice: Undefined variable: construct in C:\wamp\www\i-document\search.php on line 41 1 results found! Thankz. <html> <body> <form id="form1" method="GET" action="search.php"> <table width="446" height="135" border="1" align="center"> <tr> <td height="31" colspan="2" align="center" valign="middle" bgcolor="#990000"><span class="style1 style2">Search :</span></td> </tr> <tr> <td width="374" height="96" align="center" valign="middle" bgcolor="#990000"><span class="style1 style2"> <label> <div align="left">Keyword : <input name="search" type="text" id="search" size="40" /> </div> </label> </span> <td width="56" align="center" valign="middle" bgcolor="#990000"> <div align="left"> <input type = "submit" name="submit" value="search" /> </div></td> </tr> </table> </form> </body> </html> [b][u]search.php[/u][/b] <html> <title>Search</title> </head> <body><br /><br /> <div class="MySearch"></div><br /> <?php //Get data $button = $_GET['submit']; $search = $_GET['search']; if (!$button) echo "You didn't submit a keyword."; else { if (strlen($search)<=1) echo "Search term too short"; else { echo "You searched for <b>$search</b><hr size='1'>"; //connect to database mysql_connect("localhost","root",""); mysql_select_db("idoc"); //explode search term $search_exploded = explode(" ",$search); foreach($search_exploded as $search_each); { //Construct Query $x++; if ($x==1) $construct .= "file_name LIKE '%$search_each%'"; else $construct .= " OR file_name LIKE '%$search_each%'"; } //echo out construct $construct = "SELECT * FROM document WHERE $construct"; $run = mysql_query($construct); $foundnum = mysql_num_rows($run); if ($foundnum==0) echo "No results found"; else { echo "$foundnum results found!<p>"; while ($runrows = mysql_fetch_assoc($run)) { //Get data $ref = $runrows['file_ref']; $filename = $runrows['file_name']; $owner = $runrows['owner']; $url = $runrows['url']; echo " <table> <tr> <td> $ref </td> <td> $filename </td> <td> $owner </td> <td><a href='$url'>$url</a></td> </tr> </table> "; } } } } ?> Hello , i need some help on this line. Line: $compose_a = mysql_query("SELECT * FROM users WHERE username LIKE '%". realEscape($sendto) ."%' LIMIT 1") or die(mysql_error()); From the code : <?php if(isset($_GET['usercp']) && $_GET['send'] == 'true') { if($_POST['sendtitle'] == "") { echo "You need to have a message title."; } else { if($_POST['sendto'] == "") { echo "You must enter the username of the user you wish to send a message to."; } else { if($_POST['sendtext'] == "") { echo "You have not entered anything to send"; } else { $sendto = str_replace('_', ' ' , $_POST['sendto']); $compose_a = mysql_query("SELECT * FROM users WHERE username LIKE '%". realEscape($sendto) ."%' LIMIT 1") or die(mysql_error()); if(mysql_num_rows($compose_a) >= 1) { While($compose_b = mysql_fetch_array($compose_a)) { $sendto = $compose_b['id']; } mysql_query("INSERT INTO `notifications` (ipaddress, senderid, recieverid, sent, title, text) VALUES ('". $_SERVER['REMOTE_ADDR'] ."', '". $_SESSION['id'] ."', '" . $sendto . "', NOW(), '". htmlspecialchars($_POST['sendtitle']) ."', '". htmlspecialchars($_POST['sendtext']) ."')") or die(mysql_error()); echo "Message has been sent."; } else { echo "The username you entered does not Exist"; } } } } } ?> The $sendto is a username. i want to make it so if a user puts a Uppercase letter or a lowercase letter or a space where a '_' should be. it still matchs whats in the database. if you find a better way of doing this please post it Hi there Im trying to add a search feature to my pagination but with some googling and searching have had no luck and have also had no luck trying myself this is what i have so far Form Code: [Select] <form action="publist.php" method="post"> Search: <input type="text" name="search"> By: <select name="by"> <option value="name" selected="selected">Name</option> <option value="town">Town</option> <option value="county" >County</option> </select> Results Per Page: <select name="perpage"> <option value="10" selected="selected">10</option> <option value="25">25</option> <option value="50" >50</option> </select> <input type="hidden" name="hidden"> <input type="submit" value="Search"> </form> Related code: if(isset($_POST['hidden'])){ $by = $_POST['by']; $search = $_POST['search']; $sql = "SELECT * FROM table WHERE approved = 'Yes' AND '. $by .' = '. $search .' LIMIT $offset, $rowsperpage"; }else{ $sql = "SELECT * FROM table WHERE approved = 'Yes' LIMIT $offset, $rowsperpage"; } $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); while ($list = mysql_fetch_assoc($result)) { echo' <table width="700" border="1"> <tr> <td colspan="3">'. $list['name'] .'</td> </tr> <tr> <td height="24">Town: '. $list['town'] .'</td> <td>County: '. $list['county'] .'</td> <td>Postcode: '. $list['postcode'] .'</td> </tr> <tr> <td>Contact Number: '. $list['phone'] .'</td> <td>Email: '. $list['pubemail'] .'</td> <td><a href="info.php?id='. $list['ID'] .'">More Information</a></td> </tr> </table><br>'; } But when i try the search it comes out blank, Any help would be great Thanks, Blink359 I have a number of records of the html sections of a series of Google Earth placemarks that I managed to extract from the raw kml file. The purpose of the exersize was to then use the simplehtmldom.php api to extract the DATA from the raw html code. Some of the process is going well... and some is NOT. I have found that if I modify the raw html code by entering ID attributes into the html code the simplehtmldom api has an easy time identifying the desired data, and the data can be far 'cleaner' by entering an id attribute as 'close' to the data as possible. But doing a php text search and replace often requires finding a 'unique' identifyable portion of the html code and THEN placing the 'id' attribute in a nearby html tag because the desired data is nested inside a non-unique tag. As in I can identify a SPECIFIC <td> tag section where the data i desire is located but the data is nested inside a <font> tag inside the <td> cluster. Hence my problem... If I do a search in the following code... Code: [Select] <td><b><font size="+2" color="#FF0000">Neighborhood:</font> <font size="+2" color="#0000FF">City of Sidney</font></b></td> I can locate the 'Neighborhood:' string because it is unique in the whole html code. Then by some charcter counting I am desiring to put my 'id' attribute in the NEXT font tag because it surrounds the desired data the 'City of Sidney'... as in... Code: [Select] <td><b><font size="+2" color="#FF0000">Neighborhood:</font> <font id="neighborhood" size="+2" color="#0000FF">City of Sidney</font></b></td> With this modification the desired data is easily found and cleanly produced. But the html code while all operating correctly in a web page is not all identicle from a 'whitespace' point of view AND thus my problem. If I search the following code... Code: [Select] <td> <b><font size="+2" color="#FF0000">Neighboorhood:</font> <font size="+2" color="#0000FF">Greenacre</font></b> </td> While being identical as far as html is concerned if I search this code for the 'Neighboorhood:' identifier I find it... but then attempting to place the id tag into the NEXT font tag is being problematic. What i seem to need is a function that once the 'Neighboorhood:' string position is identied and noted in the whole of the html code, to FIND and modify the NEXT occurance of a font tag no matter what whitespace (or special charachters) may be occuring. Any suggestions?? eatc7402 Good morning, Its about this website www.deltaboatcenter.nl Boats page! I wanna search tough the boats we are selling with a seach menu, the menu is there (see website) but is got 2 scrips (below) the first one i use now the boats preview nicely on the website and work good but cant search with the boat menu for boat brands. the second one does search trough boat brands but doenst come up with boats at all.. Code: [Select] <?php include('dbclass/db.php'); include('define.php'); //////////include('pagination.class.php'); include('include/ps_pagination.php'); include_once('classes/easyphpthumbnail.class.php'); $thumb = new easyphpthumbnail; $thumb -> Thumbheight = 140; $thumb -> Thumbwidth = 200; $thumb -> Thumblocation = 'thumb/'; $thumb -> Thumbprefix = 'thumb_'; $thumb -> Thumbsaveas = 'png'; if($lang == 'eng') { $header = "header_eng.php"; $footer = "footer_eng.php"; $where = 'language_id=1'; $language =1; } elseif($lang == 'dutch') { $header = "header_dutch.php"; $footer = "footer_dutch.php"; $where = 'language_id=2'; $language =2; } elseif($lang == 'german') { $header = "header_german.php"; $footer = "footer_german.php"; $where = 'language_id=3'; $language =3; } else { $header = "header_eng.php"; $footer = "footer_eng.php"; $where = 'language_id=1'; $language =1; } //select query $obj = new Database; $obj ->select('english_boats','',$where); $query= "select * from english_boats where language_id=$language"; $pager = new PS_Pagination($obj->getConnection(),$query,5,3); $rs = $pager->paginate(); /////////var_dump($rs); ///////exit; $sel= "select * from english_boats"; /// $q=mysql_query($sel) or die mysql_error(); //generate thumbnail // include('boat_function.php'); ?> <!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> <script type='text/javascript' src='jspop/jquery.js'></script> <script type='text/javascript' src='jspop/jquery.simplemodal.js'></script> <script type='text/javascript' src='jspop/osx.js'></script> <script src="prototype.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Delta Boat company boat listing</title> <link href="boatstyle/boatstyle.css" rel="stylesheet" type="text/css" /> </head> <body class="background"> <script> function dosubmit( ) { new Ajax.Updater( 'result', 'search_boat.php', { method: 'post', parameters: $('myform').serialize() } ); $('myform').reset(); } //get_call function get_call( ) { if(document.calform.name.value=="") { //inlineMsg('name','please enter the name',20); alert('Please enter the name'); document.calform.name.focus(); return false; } var phone = /-\d{7}/ ; if(!phone.test(document.calform.tel_number.value)) { alert('Please enter the telephone number'); document.calform.tel_number.focus(); return false; } var aemail= /^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$/; if(!aemail.test(document.calform.email.value)) { alert('Please enter the valid email address'); document.calform.email.focus(); return false; } new Ajax.Updater( 'get_result', 'make_home_appointment.php', { method: 'post', parameters: $('calform').serialize() } ); $('calform').reset(); } </script> <div class="container"> <?php include($header); ?> <div class="clear"></div> <div class="line"></div> <div class="searchPanel"> <div class="searchTop"></div> <div class="clear"></div> <div class="searchMid"> <div class="searchTitle">Search</div> <div class="searchForm"> <!--javascript:get(document.getElementById('myform'));--> <form id="myform"> <input type="hidden" name="language" value="<?php echo $language;?>" /> <table class ="textboxAlign" width="100%" border="0"> <tr> <td width="38%" class="searchItem">Brand:</td> <td width="62%" class="searchItem"><div class="textboxAlign"> <select name="brand" id="brand" style="width:140px"> <option value="any">any</option> <?php while($r_b =mysql_fetch_array($q)){ ?> <option value="<?php echo $r_b['boat_brand'];?>"><?php echo $r_b['boat_brand'];?></option> <?php }?> <!-- <option value="brand B">Company B</option> <option value="brand C">Company C</option> <option value="brand D">Company D</option>--> </select> </div></td> </tr> <tr> <td nowrap="nowrap" class="searchItem">Year From:</td> <td class="searchItem"><div class="textboxAlign"> <input type="text" name="year_from" id="year_from" value="any" size="5" onfocus="if(this.value == this.defaultValue) this.value = ''"/> To: <input type="text" name="year_to" id="year_to" value="any" size="5" onfocus="if(this.value == this.defaultValue) this.value = ''"/> </div> </td> </tr> <tr> <td class="searchItem">Price From:</td> <td class="searchItem"><div class="textboxAlign"> <input type="text" name="price_from" id="price_from" value="any" size="5" onfocus="if(this.value == this.defaultValue) this.value = ''"/> To: <input type="text" name="price_to" id="price_to" value="any" size="5" onfocus="if(this.value == this.defaultValue) this.value = ''"/> </div></td></tr> <tr> <td class="searchItem" valign="top">Features:</td> <td nowrap="nowrap" class="searchItem"><input type="checkbox" name="heating" id="heating" value="588" /> Heating System</td> </tr> <tr> <td> </td> <td class="searchItem"> <input type="checkbox" name="generator" id="generator" value="661" /> Generator</td> </tr> <tr> <td> </td> <td class="searchItem" align="left"> <input type="checkbox" name="bow" id="bow_thruster" value="297" /> Bow Thruster</td> </tr> <tr> <td> </td> <td class="searchItem"> <input type="checkbox" name="stern" id="stern_thruster" value="964" /> Stern Thruster</td> </tr> <tr> <td colspan="2" align="center"> <input type="button" onclick="dosubmit()" value="Search"> <!-- <input type="button" name="button" class="button" value="Search" onclick="javascript:get(this.parentNode);" />--> </td> </tr> </table> </form> </div> </div> <div class="searchBase"></div> <div class="clear"></div> </div> <div id="result"> <div class="thumbnailsDisplayArea"> <?php if(!isset($_GET['page']) || ($_GET['page']==1)) { $i=1; } else { $i=(($_GET['page']-1)*10)+1 ; } if(mysql_num_rows($rs)>0) { while($row_fetch=mysql_fetch_assoc($rs)) {?> <?PHP $i++; ?> <div class="listPanel"> <div class="listTop"></div> <div class="listMid"> <a href="boat_detail.php?id=<?php echo $row_fetch ['boat_id'];?> & common_id=<?php echo $row_fetch['common_id']; ?>"><div class="itemName" align="left"><?php echo $row_fetch['boat_title'];?> </div></a> <div class="itemPrice"><?php echo $row_fetch['price_currency'];?> <?php echo $row_fetch['boat_price'];?></div> <div class="clear"></div> <div class="itemDescription" align="left"> <a href="boat_detail.php?id=<?php echo $row_fetch['boat_id'];?>&common_id=<?php echo $row_fetch['common_id']; ?>"><?php echo $row_fetch['boat_summary'];?></a> <div class="moreLink"><!--<a href="boat_detail.php?id=<?php //echo $value['boat_id'];?> & common_id=<?php //echo $com_id?>">more...</a>--></div> <div class="clear"></div> </div> <div class="ItemThumbnail"> <a href="boat_detail.php?id=<?php echo $row_fetch ['boat_id'];?>&common_id=<?php echo $row_fetch['common_id'];?>"> <?php ///////exit; $where=sprintf("common_id=%d",$row_fetch['common_id']); $obj ->select('boat_images','',$where); $array = $obj ->get(''); if(count($array)>0){ $imagename=$array[0]["boat_image"]; $thumb_name="thumb/thumb_$imagename"; $thumb_name=str_replace("jpg","png",$thumb_name); if(!file_exists($thumb_name)) { $thumb -> Createthumb("admin/uploads/$imagename","file"); } ?><?php } ?> <img src="<?php echo $thumb_name; ?>" border=0 /> </a><br /> </div> </div> <div class="listBase"></div> </div> <div class="clear"></div> <?php }}else { echo 'NO image found';}?> <div class="paging2"> <?php if(mysql_num_rows($rs)>0){ echo $pager->renderFullNav(); }?> <div class="clear"></div> </div></div> <div class="verticalSpacer"></div> <div class="clear"></div> <div class="line"></div> <div class="footer"> <?php include($footer);?></div> <?php include('language.php');?> <div class="clear"></div> </div> </div> </body> </html> Code: [Select] <?php include('dbclass/db.php'); include('define.php'); if($lang == 'eng') { $header = "header_eng.php"; $footer = "footer_eng.php"; $where = 'language_id=1'; $language =1; } elseif($lang == 'dutch') { $header = "header_dutch.php"; $footer = "footer_dutch.php"; $where = 'language_id=2'; $language =2; } elseif($lang == 'german') { $header = "header_german.php"; $footer = "footer_german.php"; $where = 'language_id=3'; $language =3; } else { $header = "header_eng.php"; $footer = "footer_eng.php"; $where = 'language_id=1'; $language =1; } //select query $obj = new Database; $obj ->select('english_boats','',$where); $array = $obj ->get(''); //get brands $s = "select distinct boat_brand from english_boats"; $q = mysql_query($s) or die(mysql_error()); //generate thumbnail ?> <!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> <script type="text/javascript" language="javascript"> var http_request = false; function makeRequest(url, parameters) { http_request = false; if (window.XMLHttpRequest) { // Mozilla, Safari,... http_request = new XMLHttpRequest(); if (http_request.overrideMimeType) { // set type accordingly to anticipated content type //http_request.overrideMimeType('text/xml'); http_request.overrideMimeType('text/html'); } } else if (window.ActiveXObject) { // IE try { http_request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } if (!http_request) { alert('Cannot create XMLHTTP instance'); return false; } http_request.onreadystatechange = alertContents; http_request.open('GET', url + parameters, true); http_request.send(null); } function alertContents() { if (http_request.readyState == 4) { if (http_request.status == 200) { //alert(http_request.responseText); result = http_request.responseText; document.getElementById('myspan').innerHTML = result; } else { alert('There was a problem with the request.'); } } } function get(obj) { var getstr = "?"; for (i=0; i<obj.childNodes.length; i++) { if (obj.childNodes[i].tagName == "INPUT") { if (obj.childNodes[i].type == "text") { getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&"; } if (obj.childNodes[i].type == "hidden") { getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&"; } if (obj.childNodes[i].type == "checkbox") { if (obj.childNodes[i].checked) { getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&"; } else { getstr += obj.childNodes[i].name + "=&"; } } if (obj.childNodes[i].type == "radio") { if (obj.childNodes[i].checked) { getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&"; } } } if (obj.childNodes[i].tagName == "SELECT") { var sel = obj.childNodes[i]; getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&"; } } document.getElementById('myspan').innerHTML = '<img src="images/wait30trans.gif" alt="loading" />' + 'Loading'; //setTimeout('alert(\'Surprise!\')', 5000); makeRequest('search_boat.php', getstr); } </script> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Delta Boat company about us</title> <link href="boatstyle/boatstyle.css" rel="stylesheet" type="text/css" /> </head> <body class="background"> <div class="container"> <?php include($header); ?> <div class="clear"></div> <div class="line"></div> <div class="searchPanel"> <div class="searchTop"></div> <div class="clear"></div> <div class="searchMid"> <div class="searchTitle">Search</div> <div class="searchForm"> <!--javascript:get(document.getElementById('myform'));--> <form action="javascript:get(document.getElementById('myform'));" name="myform" id="myform"> <!--<form action="" name="form">--> <table class ="textboxAlign" width="100%" border="0"> <tr> <td width="38%" class="searchItem">Brand:</td> <td width="62%" class="searchItem"><div class="textboxAlign"> <select name="brand" id="brand" style="width:140px"> <option value="any">any</option> <?php while($r_b =mysql_fetch_array($q)){ ?> <option value="<?php echo $r_b['boat_brand'];?>"><?php echo $r_b['boat_brand'];?></option> <?php }?> <!-- <option value="brand B">Company B</option> <option value="brand C">Company C</option> <option value="brand D">Company D</option>--> </select> </div></td> </tr> <tr> <td nowrap="nowrap" class="searchItem">Year From:</td> <td class="searchItem"><div class="textboxAlign"> <input type="text" name="year_from" id="year_from" value="any" size="5" onfocus="if(this.value == this.defaultValue) this.value = ''" /> To: <input type="text" name="year_to" id="year_to" value="any" size="5" onfocus="if(this.value == this.defaultValue) this.value = ''" /> </div> </td> </tr> <tr> <td class="searchItem">Price From:</td> <td class="searchItem"><div class="textboxAlign"> <input type="text" name="price_from" id="price_from" value="any" size="5" onfocus="if(this.value == this.defaultValue) this.value = ''" /> To: <input type="text" name="price_to" id="price_to" value="any" size="5" onfocus="if(this.value == this.defaultValue) this.value = ''" /> </div></td></tr> <tr> <td class="searchItem" valign="top">Features:</td> <td nowrap="nowrap" class="searchItem"><input type="checkbox" name="heating" id="heating" value="588" /> Heating Sysytem</td> </tr> <tr> <td> </td> <td class="searchItem"> <input type="checkbox" name="generator" id="generator" value="661" /> Generator</td> </tr> <tr> <td> </td> <td class="searchItem" align="left"> <input type="checkbox" name="bow" id="bow_thruster" value="297" /> Bow Thruster</td> </tr> <tr> <td> </td> <td class="searchItem"> <input type="checkbox" name="stern" id="stern_thruster" value="964" /> Stern Thruster</td> </tr> <tr> <td colspan="2" align="center"> <input type="button" name="button" class="button" value="Submit" onclick="javascript:get(this.parentNode);" /> </td> </tr> </table> </form> </div> </div> <div class="searchBase"></div> <div class="clear"></div> </div> <div id="myspan"> <div class="thumbnailsDisplayArea"> <?php if(count($array)) { while(list($k,$value) = each($array)) { $com_id = $value['common_id']; $im_where = 'common_id='.$com_id; $obj ->select('boat_images','',$im_where); $im_array = $obj ->get(''); $filename = $im_array[0]['boat_image']; ?> <div class="listPanel"> <div class="listTop"></div> <div class="listMid"> <a href="boat_detail.php?id=<?php echo $value['boat_id'];?> & common_id=<?php echo $com_id?>"><div class="itemName" align="left"><?php echo $value['boat_title'];?> </div></a> <div class="itemPrice"><?php echo $value['price_currency'];?> <?php echo $value['boat_price'];?></div> <div class="clear"></div> <div class="itemDescription" align="left"> <a href="boat_detail.php?id=<?php echo $value['boat_id'];?>&common_id=<?php echo $com_id?>"><?php echo $value['boat_summary'];?></a> <div class="moreLink"><!--<a href="boat_detail.php?id=<?php //echo $value['boat_id'];?> & common_id=<?php //echo $com_id?>">more...</a>--></div> <div class="clear"></div> </div> <div class="ItemThumbnail"><a href="boat_detail.php?id=<?php echo $value['boat_id'];?>&common_id=<?php echo $com_id?>"><?php //createThumbnail($filename);?><img src="admin/uploads/<?php echo $im_array[0]['boat_image'];?>" width="200px" height="140px" border="0" /></a></div> </div> <div class="listBase"></div> </div> <?php }}?> <div class="clear"></div> </div> </div> <div class="verticalSpacer"></div> <div class="clear"></div> <div class="line"></div> <div class="footer"> <?php include($footer);?></div> <?php include('language.php');?> <div class="clear"></div> </div> </body> </html> The strange thing is both scripts work but not good. the first one wont seach trou the boat list. and the second one does but doesent show the boats in the first place.. Does some one has any idea what i'm doing wrong? Kind regarts Hi all. This is the code I've been trying to execute. <?php // Get the search variable from URL $var = @$_GET['q'] ; $trimmed = trim($var); //trim whitespace from the stored variable // rows to return $limit=10; // check for an empty string and display a message. if ($trimmed == "") { echo "<p>Please enter a search...</p>"; exit; } // check for a search parameter if (!isset($var)) { echo "<p>No search parameter</p>"; exit; } //connect to your database ** EDIT REQUIRED HERE ** mysql_connect("localhost","*","*"); //(host, username, password) //specify database ** EDIT REQUIRED HERE ** mysql_select_db("my_db") or die("Can't select database//Does not exist."); //select which database we're using // Build SQL Query $query = "select * from people \"%$trimmed%\" order by FirstName"; // EDIT HERE and specify your table and field names for the SQL query $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); // If we have no results, offer a google search as an alternative if ($numrows == 0) { echo "<h4>Results</h4>"; echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>"; echo "<p><a href=\"http://www.google.com/search?q=" . $trimmed . "\" target=\"_blank\" title=\"Look up " . $trimmed . " on Google\">Click here</a> to try the search on Google</p>"; } // next determine if s has been passed to script, if not use 0 if (empty($s)) { $s=0; } // get results $query .= " limit $s,$limit"; $result = mysql_query($query) or die("Couldn't execute query"); // display what the person searched for echo "<p>You searched for: "" . $var . ""</p>"; // begin to show results set echo "Results"; $count = 1 + $s ; // now you can display the results returned while ($row= mysql_fetch_array($result)) { $title = $row["FirstName"]; echo "$count.) $title" ; $count++ ; } $currPage = (($s/$limit) + 1); //break before paging echo "<br />"; // next we need to do the links to other results if ($s>=1) { // bypass PREV link if s is 0 $prevs=($s-$limit); print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><< Prev 10</a>  "; } // calculate number of pages needing links $pages=intval($numrows/$limit); // $pages now contains int of pages needed unless there is a remainder from division if ($numrows%$limit) { // has remainder so add one page $pages++; } // check to see if last page if (!((($s+$limit)/$limit)==$pages) && $pages!=1) { // not last page so give NEXT link $news=$s+$limit; echo " <a href=\"$PHP_SELF?s=$news&q=$var\">Next 10 >></a>"; } $a = $s + ($limit) ; if ($a > $numrows) { $a = $numrows ; } $b = $s + 1 ; echo "<p>Showing results $b to $a of $numrows</p>"; ?> As you can see, it's pretty simple and it's got very nice explanations of what everything does. But when I try it, I get this. Quote Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in D:\Program Files\xampp\xampp\htdocs\search.php on line 36 Results Sorry, your search: "Ella" returned zero results Click here to try the search on Google Couldn't execute query I'm pretty much stuck. Any ideas what that error means? And yes, there is a entry with the name of Ella in the people table of the database. Help? I have a problem with database search for a member. I am pretty sure my sql is correct. It must be my if statements. Upon submitting the search for a member, even if there is not a match, the link appears for the member that was entered into the search. I only want the link to show up if there is a match. Thank you in advance. Code: [Select] <?php error_reporting(E_ALL); require_once("./include/membersite_config.php"); //session_start();//FOR GETTING USER ONLINE SCRIPT header("Cache-Control: nocache"); header("Expires: 0"); if(!$fgmembersite->CheckLogin()) { $fgmembersite->RedirectToURL("login.php"); exit; } $currentUser=$_SESSION['name_of_user']; // set current user name logged in to $currentUser to grab his profil DB data later. if(!$fgmembersite->CheckLogin()) { $fgmembersite->RedirectToURL("login.php"); exit; } //define a maxim size for the uploaded images in Kb define ("MAX_SIZE","100"); //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } //This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. //If the error occures the file will not be uploaded. $errors=0; include 'memberHeader.php'; if (isset($_POST['submit'])) { $memberSearch=$_POST['memberSearch']; mysql_connect(" ", " ", " ") or die(mysql_error()); // info left out mysql_select_db(" ") or die(mysql_error()) ; $sql = "SELECT username FROM users WHERE username='$memberSearch'"; $result = mysql_query($sql); echo $result; if (!$result) { echo "no matching member found " . mysql_error(); exit; } if($result) { echo "Your search result link: <a href='viewProfile.php?userPage=".$memberSearch."'>click here for result</a>"; } ////////////////////////////////MEMBER SEARCH FORM////////////// } ?> <!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>Untitled Document</title> </head> <body> <p> </p><p> </p><p><? echo "<p> </p><p></p><form id='form1' name='form' method='post' action=''> Enter a member's name here to search <input type='text' name='memberSearch' id='memberSearch' /> <input type='submit' name='submit' id='submit'/> </form>"; ?> </p> </body> </html> Hi ; I have problem with search script ; This is code ; $search_form = "<form method='get' action='' ><span class='aktif'>Arama</span><input class='aktif' type='text' name='search' ><input class='aktif' type='submit'></form>"; echo $search_form ; $search = isset($_GET['search']) ? trim($_GET['search']): ''; $a1=(str_replace(' ', '',$search) ); $S1 = ' '; $S2 = ' '; $S3 = ' '; if($search != ''){ // Terimlerin Arama Kısmı $S1 = sprintf("WHERE Tetik_Ref like '%%%s%%' OR ",mysql_real_escape_string($search)); $S2 = sprintf("Marka_Model like '%%%s%%' OR",mysql_real_escape_string($search)); $S3 = sprintf("Orj_P_N like '%%%s%%'",mysql_real_escape_string($search)); } //Verilerin yazdırılma işlemi $main_query = "SELECT * FROM ats_motor $S1 $S2 $S3 "; $count_query = "SELECT COUNT(*) FROM ats_motor $S1 $S2 $S3 ";Orj_P_N column inside Original Part Numbers. Its same of "111 11 111" or "15K 1245 45" etc. When i search exact records work fine. But I search 11111111 nothing found. I search that and find str_replace function. But i cant use that. Cant import. I try change line 8 and 14. it give me error. Can anybody help me ? Thanks. Edited by Seorniyc, 15 May 2014 - 09:55 AM. Looking for some technical assistance on a property search query im having some problems with on WP. Using the Agentpress theme I have put together a client site that is fully functional, however the client has asked that the search is altered is altered slightly and i'm having trouble working out how to do it. I'm not a database / PHP person - I have managed so far, but this is beyond my understanding. I have 2 separate search query issues. The first is that my client wants the bedrooms to be searchable with the following options: 1 or more 2 or more 3 or more 4 or more The second is that they want the availability of the property to only give 2 options: Availabile properties only Include Let Agreed Here is the site: test.taylorslettings.co.uk The property data and field names I have are being automatically created by their system and provides the information in the dropdowns as you see it in the search box on the site. The theme (Agentpress) dictates the search and how it works at present. I have no idea how to alter the search so it shows presents the results to meet the clients needs. We are at the very end stages of going live, so any urgent help would be gratefully appreciated. Thanks very much. |