September 23, 2019
Hot Topics:

Creating a Code Search Engine with PHP and MySQL

  • April 11, 2007
  • By Jason Gilmore
  • Send Email »
  • More Articles »

Using the search form to search for code consisting of the keyword "array" would produce output similar to this:

Results: <br />
Chapter 5: <a href='displaycode.php?id=65'>Retrieving array keys</a>
Chapter 5: <a href='displaycode.php?id=54'>Creating an array</a>
Chapter 9: <a href='displaycode.php?id=97'>Converting an array to a delimited string</a>

Finally, the displaycode.php script is used to display the script contents. It looks like this:



  $id = mysql_real_escape_string($_GET['id']);

  $query = "SELECT id, title, chapter, code FROM code WHERE id='$id'";

  $result = mysql_query($query);

  // If results were found, output them
  if (mysql_num_rows($result) > 0) {

    $row = mysql_fetch_array($result);

    printf("<h4>Chapter %s - %s</h4>", $row['chapter'], ucfirst($row['title']));

    // Convert the newline characters and HTML entities before displaying
    printf("%s", ^nl2br^(htmlentities($row['code'])));

  } else {
    printf("No results found");


Clicking on the first result produces output similar to the following:

Chapter 5 - Retrieving array keys


$state["Delaware"] = "December 7, 1787";
$state["Pennsylvania"] = "December 12, 1787";
$state["New Jersey"] = "December 18, 1787";
$keys = array_keys($state);


I hope this tutorial sheds some insight into how you can not only use MySQL's fulltext search capabilities to perform powerful searches against your database, but also introduces some of PHP's interesting text-related functions (nl2br(), htmlentities(), and ucfirst(), to name a few). Of course, one could easily extend what was demonstrated here to implement far more powerful search capabilities, boolean searches for instance. Be sure to check out the MySQL manual for a complete accounting of what's possible!

About the Author

W. Jason Gilmore is Apress' Open Source Editorial Director, and co-founder of IT Enlightenment. He's the author of several books, including the bestselling "Beginning PHP and MySQL 5: Novice to Professional, Second Edition" (Apress, 2006. 913pp.). Jason loves receiving e-mail; so don't hesitate to write him at wjATwjgilmore.com.

Page 2 of 2

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date