Hey guys, been browsing the forum a bit and thought it'll be a good place to ask what im going to ask i've got a mysql database with 3 fields; id,name,url i just wondered if anyone here more experienced than me in php could knock up a quick search script that i can search the name field and retrieve the name back but hyperlinked to the 3rd field(url) example; id name url 1 cola www.cola.com 2 pepsi www.pepsi.com so thats what mysql table looks like... i could make a seperate table if needed or suggested, but i'd basically want to search for the term "cola" in the search box and hit submit, then be greeted with the result "cola" but also hyperlinked to "www.cola.com" thank you in advance.
Sure. <?php /** * Search database script by Dennis M. * */ // MySQL Connect Info // Just so script can be used easily... define("DB_HOST", "localhost"); define("DB_USER", "USERNAME"); define("DB_PASS", "PASSWORD"); define("DB_NAME", "DATABASE"); define("DB_TABLE","RESULT_TABLE"); // MySQL Connection mysql_connect(DB_HOST,DB_USER,DB_PASS); mysql_select_db(DB_NAME); // Do this all in a single document... so set default.. if(!isset($_GET['page'])){ $_GET['page'] = "index"; } // Now switch... switch(strtolower($_GET['page'])){ default: print "<form name=\"search\" method=\"post\" action=\"?page=results\"> <p>Search Term: <input type=\"text\" name=\"query\" /></p> <p>Search Type: <input type=\"radio\" name=\"type\" value=\"exact\" checked /> Exact Match <input type=\"radio\" name=\"type\" value=\"like\" /> Similar Match</p> <p><input type=\"submit\" value=\"Search\" /></p> </form>"; exit; break; case 'results': if($_POST['type'] == "exact"){ $query = mysql_query("SELECT * FROM ".DB_TABLE." WHERE name='".mysql_escape_string($_POST['query'])."' ORDER BY id ASC"); } else if($_POST['type'] == "like"){ $query = mysql_query("SELECT * FROM ".DB_TABLE." WHERE name LIKE '%".mysql_escape_string($_POST['query'])."%' ORDER BY id ASC"); } if($query){ $i = 1; if(mysql_num_rows($query) != 0){ while($row = mysql_fetch_array($query)){ $name = $row['name']; $url = $row['url']; $results .= $i.". <a href=\"".$url."\">".$name."</a><br />\n"; $i++; } print $results; } else { $results = "No results match your criteria!"; } } else { print "MySQL Error:<br />".mysql_error(); } break; } ?> PHP: Regards, Dennis M.
good scripts works a treat, but when i click on similar name and leave the box empty and hit search, it then pulls my entire database out, how can i prevent this?