Simple PHP search.
December 3rd, 2007 by admin
If you are a PHP coder you will most likely at some stage of your coding career need to write a search script. Many of these can become quite complex. I will show you how to write a simple bit of search code that can be altered slightly to be used for any required search.
Here is a simple bit of PHP code to search a database and return the results
First a page with a form, nothing to different here, just remember to specify names for the elements.
form.php
1 2 3 4 | <form method="post" action="search.php"> <input value="Search" size="40" name="search" type="text" /> <input value="Search" name="dosearch" type="submit" /> </form> |
Next the code that will do the actual search. Dont forget to fill in your username and password for your MYSQL database. Then edit line 11 and 12 to search your table,
search.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | mysql_connect("localhost", "user","password"); @mysql_select_db("search"); if(isset($_POST['dosearch'])) { $search = mysql_real_escape_string($_POST['search']); if(isset($search)){ $sql = mysql_query("SELECT * FROM `table` WHERE `title` LIKE '%$search%' AND `message` LIKE '%$search%'")or die(mysql_error()); $num = mysql_num_rows($sql); if($num == 0){ echo 'Sorry, no terms returned'; } else{ while($fetchterms = mysql_fetch_array($sql)){ echo $fetchterms['title']; } }}} |
Posted in PHP Code
December 11th, 2007 at 5:59 am
Good one…though its kinda straight forward