Sunday 24 November 2013

Full-Text Search using MySQL


Intended Audience

This tutorial is intended for developers using MySQL
(http://www.MySQL.com/) and PHP
(http://www.php.net) who want to create a searchable database of some sort of textual data. It will focus on the Full-text capabilities presented by MySQL, moving into the Boolean opportunities that are presented in the latest alpha version, 4.1, of MySQL.

Overview

Using directories to group articles by category is a great way to help people to navigate through many articles. At some point, however, someone will want to find all the articles that pertain to a certain topic that may not have a directory of it’s own, or may span many directories . This is what the search engine is for.

Learning Objectives

In this tutorial, you will learn:
  • How to modify your current database to accommodate Full-text searching
  • How to use a simple Full-text search to quickly gather relevant responses
  • How to execute a more complex Full-text search with Boolean capabilities
  • Tips on what to do and what not to do, as well as the security implications of some of the example scripts presented.

Definitions

MySQL – An Open Source database that is used by many PHP developers for it’s support and
speed, as well as because it’s free.

Full-text – Built in functionality in MySQL that allows users to search through certain
tables for matches to a string.

Boolean Search  A search which allows users to narrow their results through the use of
Boolean operators.

Boolean Operators – A deductive logical system by which a user can narrow
results through the use of AND, OR, XOR, and other
operators.

Background Information

Before the advent of the search engine, users had to search manually through dozens – or hundreds – of articles and tidbits to find the ones that were right for them. Nowadays, in our more user-centered world, we expect the results to come to the user, not the other way around. The search engine gets the computer to do the work for the user.

Prerequisites

  • MySQL version 3.23.23 or better for the simple Full-text searching
  • MySQL version 4.1 alpha or better for the complex Boolean searching
  • PHP & A knowledge thereof.

Synopsis


Let’s start with a quick review of our situation:

We have a database that contains articles. We might create a table of database contents using a statement like this:

CREATE TABLE articles (body
TEXT, title VARCHAR(250), id INT NOT NULL auto_increment, PRIMARY
KEY(id);


Let’s say we have about 100 of these articles, covering various topics: MySQL, PHP, and various other topics of that sort. How do the users find the tutorials they want? Remember, we need to bring the results to
the user. This is going to be a search engine operation.

Initial Ideas

When I started to work with my first database which was only a tenth of the size, my MySQL query went something like this:

SELECT * FROM articles WHERE body LIKE '%$keyword%';

This was slow and inefficient.Every time someone searched for an article, they got far too many results, and as the database grew the system became downright shameful.

So what is the solution? It’s right here: Full-text Searching.



The Solution: Setup

Full-text Search is a feature introduced to MySQL in version 3.23.23. This is how I used it to fix my problem:

I started out with an update to my table:


ALTER TABLE articles ADD FULLTEXT(body, title);

This set ups our Full-text index. The (body, title) part tells us that we can search the body and title for keywords later on. We’ll find out how to use this later, once we’ve overcome a potential problem.

In my original database BLOB was my datatype for the body of the article. What’s the problem, you ask? BLOBs are meant primarily for binary data. What use is searching binary data? MySQL has been programmed not to index BLOB datatypes for Full-text searching. If you try to index BLOB
datatypes, you get an Error 140.

The fix for this is simple:


ALTER TABLE articles MODIFY body TEXT;



That switches datatype from BLOB to TEXT, thus making a useful column for searching.


Codeigniter MVC class and functions template

Hi this is Anjaneya Vadivel, Every time I make a website I usually try to plan my classes out ahead of time in a regular text file, this small step will reduce the amount of time spent figuring out how to design my application considerably. I find this especially useful when working with CodeIgniter. I can even create all the files ahead of time, (usually I use the touch command in terminal to do it quickly).

This is how my template might look before being filled out :

Example Class Template

MODEL: (classes with functions to GET/INSERT/UPDATE/DELETE from the database, called from controller classes)

model_class.php
[some functions listed here]

CONTROLLER: (functions to handle user requests : call model functions and load up views)

class_a.php
[some functions listed here]

class_b.php
[some functions listed here]

VIEW: (PHP files that contain the necessary html to see the page, loaded from controller classes)

template/html_head.php
template/html_tail.php

Example Blog Class Template

Once again this is not a completed template below as the functions would usually be filled in with as much information as I can plan before starting the actual application. This means thinking of all parameter names, and the insides of the functions before starting.

MODEL:

posts_model.php

get_posts()
get_post_by_id()
get_tags_by_post_id()
insert_post()
update_post_by_id()
delete_post_by_id()
etc…

CONTROLLER:

posts.php

index()
etc

pages.php

index($page)
etc…

VIEW:

template/html_head.php
template/html_tail.php
post/single_view.php
post/multi_view.php
page/contact_us
page/home
etc…

Why plan?

If you don’t already create a template to help organize your thoughts when programming, you should try it! It’s the easiest way to see the amount of work that needs to be done, divide work among multiple people easily, and help make MVC programming a little more intuitive.

How much planning do you do before starting your application?

Simple PHP Code in Codeigniter

This section will show you how to create the admin page for our blog, with pages to create and edit blog posts. By the end of this part you should have a functioning admin page (that requires login!) displaying a list of posts from the database, with links to view, edit, or delete the post.

We’re gonna want to add the methods to insert, update, and delete posts. With CodeIgniter manipulating database data is simplified.

Go back to the Posts model located at :

/application/models/posts.php

Copy the extra methods to our Post model from the code below :

  1. <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
  2. class Posts extends CI_Model
  3. {
  4.        
  5.         function __construct()
  6.         {
  7.                 parent::__construct();
  8.         }
  9.         // If $postId is NULL, gets all posts, otherwise get single post from db
  10.         // returns $post[]
  11.         public function get_posts($postId)
  12.         {
  13.                 $post=array();
  14.                 if ($postId !== null){         
  15.                         $query = $this->db->get_where('posts', array('id' =>$postId));
  16.                         if ($query->num_rows() == 1) { 
  17.                                 foreach($query->result() as $row){
  18.                                 $post['id'] = $row->id;
  19.                                 $post['title'] = $row->title;
  20.                                 $post['summary'] = $row->summary;
  21.                                 $post['content'] = $row->content;
  22.                                 }
  23.                                 return $post;
  24.                         }      
  25.                 } else {
  26.                         $query = $this->db->get('posts');
  27.                         if ($query->num_rows() !== 0 ){
  28.                                 foreach($query->result() as $row){
  29.                                 $post['id'][] = $row->id;
  30.                                 $post['title'][] = $row->title;
  31.                                 $post['summary'][] = $row->summary;
  32.                                 $post['content'][] = $row->content;
  33.                                 }
  34.                                 return $post;
  35.                         }
  36.                        
  37.                 }              
  38.         }
  39.         function insert_post($data){
  40.                 $this->db->insert('posts', $data);
  41.                 return;
  42.         }
  43.         function update_post($postId, $data){
  44.                 $id = $postId;         
  45.                 $this->db->where('id',$id);
  46.                 $this->db->update('posts', $data);
  47.                 return;
  48.         }
  49.         function delete_post($postId){
  50.                 $id = $postId;         
  51.                 $this->db->delete('posts',array('id' => $id));
  52.                 return;
  53.         }
  54. }

Views

Once again we’re going to need to create a few simple view files for our admin index page, a new html head wrapper file that will have a ‘Logout’ link instead of an ‘Admin’ link, and forms for creating/editing posts.

Create admin_html_head.php at this location :

/application/views/template/admin_html_head.php

Copy the code below :
  1. <!DOCTYPE html>
  2.         <head>
  3.                 <link rel="stylesheet" type="text/css" href="<?php echobase_url('style.css');?>">
  4.         </head>
  5.         <body>
  6.                 <h1><?php echo anchor('','My Blog'); ?></h1>
  7.                 <div id="loginDiv"><?php echo anchor('admin/logout','Logout');?></div>
  8.                 <hr/>

Create index.php at this location :

/application/views/admin/index.php

Copy the code below :
  1. <?php
  2.         echo '<p>Welcome To The Admin Page '.$username.'! All posts available for edit or deletion is listed below.</p><br/>';
  3.         echo anchor('admin/create','Create New Post');
  4.         $count = count($post['id']);
  5.         for ($i=0;$i<$count;$i++)
  6.         {
  7.                 echo '<div class="postDiv">';
  8.                 echo '<h4>'.$post['title'][$i];
  9.                 echo anchor('blog/view/'.$post['id'][$i],' [view]');
  10.                 echo anchor('admin/edit/'.$post['id'][$i],' [edit]');
  11.                 echo anchor('admin/delete/'.$post['id'][$i],' [delete]</h4>');
  12.                 echo '<p>'.$post['summary'][$i].'</p>';
  13.                 echo '</div>';
  14.         }
  15. ?>

reate create.php at this location :

/application/views/admin/create.php

Copy the code below :
  1. <?php
  2.         echo validation_errors();
  3. ?>
  4.         <h4>Create A New Post Below</h4>
  5.         <form action="" method="post" >
  6.         <p>Title:</p>
  7.         <input type="text" name="title" size="50"/><br/>       
  8.         <p>Summary:</p>
  9.         <textarea name="summary" rows="2" cols="50"></textarea><br/>
  10.         <p>Post Content:</p>
  11.         <textarea name="content" rows="6" cols="50"></textarea><br/>
  12.         <input type="submit" value="Save" />
  13. <?php
  14.         echo anchor('admin','Cancel');
  15. ?>
  16.         </form>

Create edit.php at this location :

/application/views/admin/edit.php

Copy the code below :
  1. <?php
  2.         echo validation_errors();
  3. ?>
  4.         <h4>Edit "<?php echo $post['title']; ?>" Below</h4>
  5.         <form action="" method="post" >
  6.                 <p>Title:</p>
  7.                 <input type="text" name="title" size="50" value="<?php echo$post['title']; ?>"/><br/> 
  8.                 <p>Summary:</p>
  9.                 <textarea name="summary" rows="2" cols="50"><?php echo$post['summary']; ?>
  10.                 </textarea><br/>
  11.                 <p>Post Content:</p>
  12.                 <textarea name="content" rows="6" cols="50"><?php echo$post['content']; ?>
  13.                 </textarea><br/>
  14.                 <input type="submit" value="Save" />
  15. <?php
  16.         echo anchor('admin','Cancel');
  17. ?>
  18.         </form>

Simple CRUD in Laravel Framework

Creating, reading, updating, and deleting resources is used in pretty much every application. Laravel helps make the process easy using re...