James John – Software Engineer

Searching MySQL Database using PHP

Searching MySQL Database using PHP

Hi all,

To all gurus in PHP, i know this is just a piece of cake….but i confess, during my newbie day it tortured me seriously and i want to make it not to torture newbies of today. :P :D

Lets Begin:

Now you already have your data in the database, all you want is to search the data and callout related data following it,

In a file called search.php

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>Search</title>
  6. </head>
  7. <body>
  8. <!-- Creating a form for the search -->
  9. <form action="" method="post">
  10. <input type="text" name="keyword" placeholder="Enter keyword to search" /><br/>
  11. <input type="submit" value="Search" /></form>
  12. <?php
  13. //Now the PHP code goes
  14. //defining a variable before using it
  15. if(isset($_POST['keyword']))
  16. {
  17. //now assigning to a variable
  18. $word = $_POST['keyword'];
  19. //if the user entered with an empty textbox
  20. if(!$word)
  21. {
  22. //you can add you action
  23. }
  24. //If not found
  25. elseif(mysql_num_rows(mysql_query("select * from your_table where your_column_ like'%$word%'"))<=0)
  26. {
  27. echo "Sorry, no results found";
  28. }
  29. else
  30. {
  31. ?><center>Results</center><?php
  32. //now query out your db
  33. $query = mysql_query("select * from table_name where column_name like'%$word%'")or die(mysql_error());
  34. while($row=mysql_fetch_array($query))
  35. {
  36. //fetch data in db
  37. }
  38. }
  39. }
  40. ?>
  41. </body></html>

James John

Software Engineer