Wednesday, December 18, 2013

How To Generate Dynamic LIKE Clause With Parentheses Using Codeigniter Active Record?

If you want to make dynamic and custom LIKE clause using Codeigniter active record, following function will be useful.
For Example
The number of tags and values is unknown. Arrays are created dynamically. This function can help you to accomplish what you want to it.
//To add parentheses around the LIKE clauses
function make_like_conditions (array $fields, $search_text) {
    $likes = array();
    foreach ($fields as $field) {
        $likes[] = "$field LIKE '%$search_text%'";
    }
    return '('.implode(' || ', $likes).')';
}

function do_something()
{
   $search_fields = array(
    'field_1',
    'field_2',
    'field_3',
  );

  $search_text = "apple";

  $like_conditions = $this->make_like_conditions($search_fields, $search_text);
  $query = $this->db->from('sometable')->where($like_conditions)->get();
  return $query->result();
}


Source: http://stackoverflow.com/a/16925449

Tuesday, December 17, 2013

How To Display Search Results With Multiple Tags Using CodeIgniter Active Record?

I was working on a tags system in CI and, what I need was to generate a query that should only display posts with selected tags (i.e. only that have the tags) as an output. After searching many hours in internet, I saw this amazing blog with possible solutions.
http://tagging.pui.ch/post/37027745720/tags-database-schemas
Because of my database struture, i liked "Toxi Solution". The main advantage of this solution is that it is more normalized than the other solutions, and that you can have unlimited number of tags per post.


Since I need to only show posts that have the tags. So I have to do Intersection (AND) query.
Intersection (AND)
Query for “bookmark+webservice+semweb” 

SELECT b.*
FROM tagmap bt, bookmark b, tag t
WHERE bt.tag_id = t.tag_id
AND (t.name IN ('bookmark', 'webservice', 'semweb'))
AND b.id = bt.bookmark_id
GROUP BY b.id
HAVING COUNT( b.id )=3
I have to convert this query using Codeigniter's Active record.
Steps To Display Search Results With Multiple Tags using Codeigniter activerecord are follows
1. Joined tags table to posts table
2. Use where_in active record
3. Use group_by active record
4. Use having account record
5. Use custom count statement inside having statement

Example

$this->db->join('tagmap', 'bookmark.bookmark_id = tagmap.bookmark_id', 'left');
$this->db->join('tag', 'tag.tag_id = tagmap.tag_id', 'left');   
          
    
$a_tag = array(); 
//I am using static array for this example only (It can be dynamic array from Front end (eg. user inputs))
$filter_tag = array("bookmark", "webservice", "semweb");
      
$a_tag = explode(",", trim($filter_tag)); // Your tags as an array.
     
$a_tag  = array_unique($a_tag);  // to have unique array (protect duplicate array values)
     
$tag_count = count($a_tag); // count the number of elements in the array
     
$this->db->where_in('tag.name', $a_tag);
     
$this->db->group_by('bookmark.bookmark_id');
     
$count = "COUNT(bookmark.bookmark_id) = $tag_count";   // Custom string 
     
$this->db->having($count);

$query = $this->db->get('bookmark');   

return ($query->num_rows() > 0)  ? $query->result() : FALSE;    

In this way you can retrieve posts that belong to a specific group of tags using Codeigniter Activerecord.

Ref: http://tagging.pui.ch/post/37027745720/tags-database-schemas

Thursday, December 12, 2013

How To Remove Stop words From The String Using PHP?

I want to strip whole bad words from a string wherever they are inside the string.
I have created an array of forbidden words or stop words.
$string = 'sand band or nor and where whereabouts foo';
$stopwords = array("or", "and", "where");
There are two ways to achieve it. For example:
Alternative 1
echo preg_replace("\b$stopwords\b", "", $string);
//output : sand band  nor   whereabouts foo
Alternative 2
foreach ($stopwords as &$word) {
    $word = '/\b' . preg_quote($word, '/') . '\b/';
}
echo preg_replace($stopwords, '', $string);
//output : sand band  nor   whereabouts foo
Ref: http://codepad.org/lrXknCO4 && http://stackoverflow.com/a/9342200

Create Array Without Keys From Comma Separated String Using PHP

You can't have an array without keys. But there is workaround to make it possible.
Grab the comma separated string and use explode function to create array. Use the implode function on resulting array, and you will get the nice array without keys.
Example
$strings =  "my, name, is, Anup";
$arraydata = explode(",", trim($strings));
echo '$arr = array("'.implode('", "', $arraydata).'");';
//output 
// $arr = array("my", "name", "is", "Anup");

X-editable and Bootstrap Using Image field To Trigger Select

You can use icons in an interface to trigger a select popup with X-editable and Bootstrap and replace the text content with an image.

HTML:
<p>X-editable: single reqular checkbox</p>
<div style="margin: 150px">
    <img id="check" src="http://png-4.findicons.com/files/icons/2152/snowish/128/dialog_warning.png"/>
</div>

JS:
$('#check').editable({
    type: 'checklist',
    url: '/post',    
    pk: 1, 
    placement: 'right',
    title: 'Option 1',
    source: {'1': 'enabled'},
    emptytext: 'disabled',
    success: function(data, config) {
        if(data = '1'){
            $("#check").attr("src", "http://png-2.findicons.com/files/icons/808/on_stage/128/symbol_check.png");
        }else{
            $("#check").attr("src", "http://png-4.findicons.com/files/icons/2152/snowish/128/dialog_warning.png");
        }
    }
});
Demo

Source: http://stackoverflow.com/a/16878660

Wednesday, December 11, 2013

Custom Full-text Search Against Stopwords And Special Characters Using PHP And Mysql

I'm not sure if this is the best way.
To clean I pass the data through this class, all it does is strip out any special characters, and a list of stop words that I don't want to include in searches:
<?php 
class Cleaner {

    var $stopwords = array(" find ", " about ", " me ", " ever ", " each ", " update ", " delete ", " add ", " insert ",
 " where ", " i ", " a ", " my ");//you need to extend this big time.

    var $symbols = array('/','\\','\'','"',',','.','<','>','?',';',':','[',']','{','}','|','=','+',
'-','_',')','(','*','&','^','%','$','#','@','!','~','`');

    function parseString($string) {
        $string = ' '.$string.' ';
        $string = $this->removeStopwords($string);
        $string = $this->removeSymbols($string);
        return $string;
    }

    function removeStopwords($string) {
        for ($i = 0; $i < sizeof($this->stopwords); $i++) {
            $string = str_replace($this->stopwords[$i],' ',$string);
        }

        return trim($string);
    }

    function removeSymbols($string) {
        for ($i = 0; $i < sizeof($this->symbols); $i++) {
            $string = str_replace($this->symbols[$i],' ',$string);
        }

        return trim($string);
    }
}

Source : http://stackoverflow.com/a/9082165

Monday, December 9, 2013

List of Swedish Stop words hard coded in the php array

These are the Swedish stop words which can be used to filter search function in mysql and PHP.
$stopwords = array("aderton", "adertonde", "adjö", "aldrig", "alla", "allas", "allt", "alltid", "alltså", "än", "andra", "andras", "annan", "annat", "ännu", "artonde", "artonn", "åtminstone", "att", "åtta", "åttio", "åttionde", "åttonde", "av", "även", "båda", "bådas", "bakom", "bara", "bäst", "bättre", "behöva", "behövas", "behövde", "behövt", "beslut", "beslutat", "beslutit", "bland", "blev", "bli", "blir", "blivit", "bort", "borta", "bra", "då", "dag", "dagar", "dagarna", "dagen", "där", "därför", "de", "del", "delen", "dem", "den", "deras", "dess", "det", "detta", "dig", "din", "dina", "dit", "ditt", "dock", "du", "efter", "eftersom", "elfte", "eller", "elva", "en", "enkel", "enkelt", "enkla", "enligt", "er", "era", "ert", "ett", "ettusen", "få", "fanns", "får", "fått", "fem", "femte", "femtio", "femtionde", "femton", "femtonde", "fick", "fin", "finnas", "finns", "fjärde", "fjorton", "fjortonde", "fler", "flera", "flesta", "följande", "för", "före", "förlåt", "förra", "första", "fram", "framför", "från", "fyra", "fyrtio", "fyrtionde", "gå", "gälla", "gäller", "gällt", "går", "gärna", "gått", "genast", "genom", "gick", "gjorde", "gjort", "god", "goda", "godare", "godast", "gör", "göra", "gott", "ha", "hade", "haft", "han", "hans", "har", "här", "heller", "hellre", "helst", "helt", "henne", "hennes", "hit", "hög", "höger", "högre", "högst", "hon", "honom", "hundra", "hundraen", "hundraett", "hur", "i", "ibland", "idag", "igår", "igen", "imorgon", "in", "inför", "inga", "ingen", "ingenting", "inget", "innan", "inne", "inom", "inte", "inuti", "ja", "jag", "jämfört", "kan", "kanske", "knappast", "kom", "komma", "kommer", "kommit", "kr", "kunde", "kunna", "kunnat", "kvar", "länge", "längre", "långsam", "långsammare", "långsammast", "långsamt", "längst", "långt", "lätt", "lättare", "lättast", "legat", "ligga", "ligger", "lika", "likställd", "likställda", "lilla", "lite", "liten", "litet", "man", "många", "måste", "med", "mellan", "men", "mer", "mera", "mest", "mig", "min", "mina", "mindre", "minst", "mitt", "mittemot", "möjlig", "möjligen", "möjligt", "möjligtvis", "mot", "mycket", "någon", "någonting", "något", "några", "när", "nästa", "ned", "nederst", "nedersta", "nedre", "nej", "ner", "ni", "nio", "nionde", "nittio", "nittionde", "nitton", "nittonde", "nödvändig", "nödvändiga", "nödvändigt", "nödvändigtvis", "nog", "noll", "nr", "nu", "nummer", "och", "också", "ofta", "oftast", "olika", "olikt", "om", "oss", "över", "övermorgon", "överst", "övre", "på", "rakt", "rätt", "redan", "så", "sade", "säga", "säger", "sagt", "samma", "sämre", "sämst", "sedan", "senare", "senast", "sent", "sex", "sextio", "sextionde", "sexton", "sextonde", "sig", "sin", "sina", "sist", "sista", "siste", "sitt", "sjätte", "sju", "sjunde", "sjuttio", "sjuttionde", "sjutton", "sjuttonde", "ska", "skall", "skulle", "slutligen", "små", "smått", "snart", "som", "stor", "stora", "större", "störst", "stort", "tack", "tidig", "tidigare", "tidigast", "tidigt", "till", "tills", "tillsammans", "tio", "tionde", "tjugo", "tjugoen", "tjugoett", "tjugonde", "tjugotre", "tjugotvå", "tjungo", "tolfte", "tolv", "tre", "tredje", "trettio", "trettionde", "tretton", "trettonde", "två", "tvåhundra", "under", "upp", "ur", "ursäkt", "ut", "utan", "utanför", "ute", "vad", "vänster", "vänstra", "var", "vår", "vara", "våra", "varför", "varifrån", "varit", "varken", "värre", "varsågod", "vart", "vårt", "vem", "vems", "verkligen", "vi", "vid", "vidare", "viktig", "viktigare", "viktigast", "viktigt", "vilka", "vilken", "vilket", "vill");

Source: http://www.ranks.nl/stopwords/swedish.html

Thursday, December 5, 2013

How To Use Ajax with jQuery and CodeIgniter Tutorial?

You can easily use ajax with jQuery and Codeigniter. Below is the tutorial with complete source code on how to use ajax with jQuery and Codeigniter.

Controller : ajax_sample.php
<?php
class Ajax_sample extends CI_Controller {
 
    function __construct(){
        parent::__construct();
        $this->load->helper('url');
    }
 
    /*
     * show list as a table, get data from "test_model"
     * */
    function get_list_view(){
 
        $this->load->model('test_model');
 
        $data = array();
 
        $data['title'] = 'Lorem ipsum';
        $data['list'] = $this->test_model->get_data();
 
        $this->load->view('sample_table', $data);
 
    }
 
    function index(){
        $this->load->view('test_page');
    }
 
}
Model : test_model.php
<?php
 
//file: application/models/test_model.php
 

class Test_model extends CI_Model {
 
    function __construct(){
        parent::__construct();
    }
 
    function get_data(){
 
        $type = $this->input->post('type');
 
        if($type != 1){
            return array();
        }
 
        return array(
            array(
                'name' => 'Abigail',
                'email' => 'ut.sem.Nulla@duinecurna.org',
                'registered_date' => '01/17/2014'
            ),
            array(
                'name' => 'Ralph',
                'email' => 'ultrices.posuere@Sed.org',
                'registered_date' => '10/08/2013'
            ),
        );
    }
 
}
Views: test_page.php
<html>
<head>
<title>Ajax sample (with CodeIgniter)</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <script type="text/javascript">
 var controller = 'ajax_sample';
 var base_url = '<?php echo site_url(); //you have to load the "url_helper" to use this function ?>';

function load_data_ajax(type){
 $.ajax({

 'url' : base_url + '/' + controller + '/get_list_view',
 'type' : 'POST', //the way you want to send data to your URL
 'data' : {'type' : type},
 'success' : function(data){ //probably this request will return anything, it'll be put in var "data"

var container = $('#container'); //jquery selector (get element by id)
 if(data){
container.html(data);
 }
 }
 });
 }
 </script>

 </head>
 <body>
 <button onclick="load_data_ajax(1)">Load list (type 1)</button>
 <button onclick="load_data_ajax(2)">Load list (type 2)</button>

 <hr />

 <div id="container">
</div>
</body>
</html>
Views: sample_table.php

<?php if(isset($title) && !empty($title)) : ?>
    <h1><?php echo $title; ?></h1>
<?php endif; ?>

<?php if(isset($list) && count($list)) : ?>
    <table>
        <thead>
            <tr>
             <th>Name</th>
             <th>E-mail</th>
             <th>Registered date</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($list as $row) : ?>
                <tr>
                    <td><?php echo $row['name']; ?></td>
                    <td><?php echo $row['email']; ?></td>
                    <td><?php echo $row['registered_date']; ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php else : ?>
    <h3>No results found!</h3>
<?php endif; ?>


Source: https://github.com/alyssonajackson/sample_ajax_with_jquery_and_codeigniter