Sunday, August 31, 2014

how can use protected CI_DB_active_record->_compile_select() method as public get_compile_select()

1. copy system/core/Loader.php to application/core/Loader.php

2. copy system/database/DB.php to application/database/DB.php

3. open application/core/Loader.php, change method like this below


public function database($params = '', $return = FALSE, $active_record = NULL)
    {
        // Grab the super object
        $CI =& get_instance();
       
        // Do we even need to load the database class?
        if (class_exists('CI_DB') AND $return == FALSE AND $active_record == NULL AND isset($CI->db) AND is_object($CI->db))
        {
            return FALSE;
        }

        // BOROO edited this code [start]
        // _compile_select удамших функцийг ашиглахын тулд өөрчлөлт хийв
        //require_once(BASEPATH.'database/DB.php');
        require_once(APPPATH.'database/DB.php');
        // BOROO edited this code [start]

        if ($return === TRUE)
        {
            return DB($params, $active_record);
        }

        // Initialize the db variable.  Needed to prevent
        // reference errors with some configurations
        $CI->db = '';

        // Load the DB class
        $CI->db =& DB($params, $active_record);
    }


4. open application/database/DB.php, edit method like this below


require_once(BASEPATH . 'database/DB_driver.php');

    if (!isset($active_record) OR $active_record == TRUE) {
        require_once(BASEPATH . 'database/DB_active_rec.php');

        if (!class_exists('CI_DB')) {
            // BOROO edited this code [start]
            if(CI_VERSION == '2.1.4') {
                eval('class CI_DB extends CI_DB_active_record {
                    public function get_compile_select() {
                        return $this->_compile_select();
                    }
                }');
            } else {
                eval('class CI_DB extends CI_DB_active_record { }');
            }
            // BOROO edited this code [end]
        }
    } else {
        if (!class_exists('CI_DB')) {
            eval('class CI_DB extends CI_DB_driver { }');
        }
    }


5. now you can use get_compile_select()


in base_model extends CI_Model {

public function get_compile_select() {
        $this->{$this->db_group}->select('*');
        $this->{$this->db_group}->from($this->table);
        $this->{$this->db_group}->order_by("title", "asc");
        $this->{$this->db_group}->limit(100, 0);
        $subQuery = $this->{$this->db_group}->get_compile_select();
        return $subQuery;
    }
.................................
}

public category_model extends base_model {
..................................
}


in controller


echo "<hr>";
        echo $this->category_model->get_compile_select();
        echo "<hr>";
        exit;


result

SELECT * FROM (`category`) ORDER BY `title` asc LIMIT 100

//now u can get generate sql query without running or last_query()

Saturday, August 30, 2014

Node.js custom module express http server routing response file with simple chat using socket.io

appInclude.js

var fs = require("fs");
var url = require("url");

exports.createApp = function(express){
    var options = {
       
    };

    var app = express();
    app.get('/', function(req, res){
        var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
        console.log('Request from %s', ip);
       
        res.send('Welcome to NodeJS Express Server.');
    });
    app.get('/*', function(req, res){
        console.log('Request url is ' + req.originalUrl);
       
        var uri = url.parse(req.url);
        console.log('pathname: ' + uri.pathname);
       
        if(uri.pathname.length > 0){
            //hello.txt and more file
            var fname = uri.pathname.substring(1);
            fs.exists(fname, function(exists){
                if(exists){
                    var html = fs.readFileSync(fname);
                    res.writeHead(200, {'Content-Type': 'text/html'});
                    res.end(html);
                }else{
                    res.writeHead(404);
                    res.end("FileNotFound");
                }
            });
        }else{
            res.writeHead(404);
            res.end("PageNotFound");
        }
    });
    console.log(__dirname);
    app.use(express.static(__dirname));
    return app;
};

 
app.js

var sys = require("sys");
var express = require("express");
var include = require("./appInclude");

var app = include.createApp(express);
var server = app.listen(80, function() {
    console.log('Listening on port %d', server.address().port);
});

//npm install socket.io --msvs_version=2012
var io = require('socket.io').listen(server);
io.on('connection', function (socket) {
    console.log('Client connected...');
    socket.on('join', function (data) {
        socket.nickname = data.name;
        console.log('nickname is ' + data.name);       
    });
    socket.on('messages', function (data) {
        console.log(data);
        socket.broadcast.emit('messages', data);
    });
});

AngularJs Simple Example: Post Data to PHP page

HTML
 
<!DOCTYPE html>
<html ng-app>
    <head>
        <title>AngularJs Post Example: DevZone.co.in </title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
        <style>
            #dv1{
                border:1px solid #DBDCE9; margin-left:auto;
                margin-right:auto;width:220px;
                border-radius:7px;padding: 25px;
            }
 
            .info{
                border: 1px solid;margin: 10px 0px;
                padding:10px;color: #00529B;
                background-color: #BDE5F8;list-style: none;
            }
            .err{
                border: 1px solid;  margin: 10px 0px;
                padding:10px;  color: #D8000C;
                background-color: #FFBABA;   list-style: none;
            }
        </style>
    </head>
    <body>
        <div id='dv1'>
            <form ng-controller="FrmController">
                <ul>
                    <li class="err" ng-repeat="error in errors"> {{ error}} </li>
                </ul>
                <ul>
                    <li class="info" ng-repeat="msg in msgs"> {{ msg}} </li>
                </ul>
                <h2>Sigup Form</h2>
                <div>
                    <label>Name</label>
                    <input type="text" ng-model="username" placeholder="User Name" style='margin-left: 22px;'>
                </div>
                <div>
                    <label>Email</label>
                    <input type="text" ng-model="useremail" placeholder="Email" style='margin-left: 22px;'>
                </div>
                <div>
                    <label>Password</label>
                    <input type="password" ng-model="userpassword" placeholder="Password">
                </div>
                <button ng-click='SignUp();' style='margin-left: 63px;margin-top:10px'>SignUp</button>
            </form>
        </div>
 
        <script type="text/javascript">
            function FrmController($scope, $http) {
                $scope.errors = [];
                $scope.msgs = [];
 
                $scope.SignUp = function() {
 
                    $scope.errors.splice(0, $scope.errors.length); // remove all error messages
                    $scope.msgs.splice(0, $scope.msgs.length);
 
                    $http.post('post_es.php', {'uname': $scope.username, 'pswd': $scope.userpassword, 'email': $scope.useremail}
                    ).success(function(data, status, headers, config) {
                        if (data.msg != '')
                        {
                            $scope.msgs.push(data.msg);
                        }
                        else
                        {
                            $scope.errors.push(data.error);
                        }
                    }).error(function(data, status) { // called asynchronously if an error occurs
// or server returns response with an error status.
                        $scope.errors.push(status);
                    });
                }
            }
        </script>
        <a href='http://devzone.co.in'>Devzone.co.in</a>
    </body>
</html>
 
 
PHP
 
<?php
 
$data = json_decode(file_get_contents("php://input"));
$usrname = mysql_real_escape_string($data->uname);
$upswd = mysql_real_escape_string($data->pswd);
$uemail = mysql_real_escape_string($data->email);
 
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('test', $con);
 
$qry_em = 'select count(*) as cnt from users where email ="' . $uemail . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
 
if ($res['cnt'] == 0) {
    $qry = 'INSERT INTO users (name,pass,email) values ("' . $usrname . '","' . $upswd . '","' . $uemail . '")';
    $qry_res = mysql_query($qry);
    if ($qry_res) {
        $arr = array('msg' => "User Created Successfully!!!", 'error' => '');
        $jsn = json_encode($arr);
        print_r($jsn);
    } else {
        $arr = array('msg' => "", 'error' => 'Error In inserting record');
        $jsn = json_encode($arr);
        print_r($jsn);
    }
} else {
    $arr = array('msg' => "", 'error' => 'User Already exists with same email');
    $jsn = json_encode($arr);
    print_r($jsn);
}
?>
 

a simple search with AngularJS and PHP

searchForm.html

<!DOCTYPE html>
<html ng-app>
<head>
<title>Search form with AngualrJS</title>
 <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
 <script src="http://code.angularjs.org/angular-1.0.0.min.js"></script>
 <script src="search.js"></script>
</head>

<body>

 <div ng-controller="SearchCtrl">
 <form class="well form-search">
  <label>Search:</label>
  <input type="text" ng-model="keywords" class="input-medium search-query" placeholder="Keywords...">
  <button type="submit" class="btn" ng-click="search()">Search</button>
  <p class="help-block">Try for example: "php" or "angularjs" or "asdfg"</p>  
    </form>
<pre ng-model="result">
{{result}}
</pre>
   </div>
</body>

</html> 
 
 
 

The AngularJS script (search.js)


function SearchCtrl($scope, $http) {
 $scope.url = 'search.php'; // The url of our search
  
 // The function that will be executed on button click (ng-click="search()")
 $scope.search = function() {
  
  // Create the http post request
  // the data holds the keywords
  // The request is a JSON request.
  $http.post($scope.url, { "data" : $scope.keywords}).
  success(function(data, status) {
   $scope.status = status;
   $scope.data = data;
   $scope.result = data; // Show result from server in our <pre></pre> element
  })
  .
  error(function(data, status) {
   $scope.data = data || "Request failed";
   $scope.status = status;   
  });
 };
}

 

The server-side script (search.php)


<?php
// The request is a JSON request.
// We must read the input.
// $_POST or $_GET will not work!

$data = file_get_contents("php://input");

$objData = json_decode($data);

// perform query or whatever you wish, sample:

/*
$query = 'SELECT * FROM
tbl_content
WHERE
title="'. $objData->data .'"';
*/

// Static array for this demo
$values = array('php', 'web', 'angularjs', 'js');

// Check if the keywords are in our array
if(in_array($objData->data, $values)) {
 echo 'I have found what you\'re looking for!';
}
else {
 echo 'Sorry, no match!';
}

 

Thursday, August 28, 2014

Left-side navbar example with collapse, extendable using jquery

<html>
<head>
    <title>Toggle</title>
    <script type="text/javascript" src="jquery-1.6.2.min.js"></script>
    <style>
        .right-menu {float:left; width:230px; padding:15px 0 0 0;}
        .right-basicmenu{float:left; width:230px; padding-top:5px;}
        .right-basicmenu a, .right-basicmenu a:visited {width:220px; display:block; padding:10px 0 10px 10px;  color:#fff; font-size:138.5%;  background-color:#016ea7; font-family:"Myriad Pro";}
        .right-basicmenu a.rsel, .right-basicmenu a.rsel:visited {font-size:138.5%; font-weight:bold; color:#fff; background-color:#016ea7; font-family:"Myriad Pro";}
             ul.style {list-style:none; padding:0; margin:0;}
             ul.style li{list-style:none;}
            .right-submenu {float:left; width:200px; padding-left:30px; margin-top:5px; background-color:#eef9ff;}
            .right-submenu li a, .right-submenu li a:visited {width:200px; padding:6px 0; color:#000; font-size:108%; font-family:"Myriad Pro"; background:none;}
            .right-submenu a.submenusel, .right-submenu a.submenusel:visited {color:#0c499c; font-size:108%; font-family:"Myriad Pro"}
    </style>
</head>
<body>
    <div class="right-menu" id="right-menu">
        <div class="right-basicmenu">
            <a href="javascript:void(0);">Adventure Tours</a>
            <div class="right-submenu">
                <ul class="style">
                    <li><a href="javascript:void(0)">*Fishing</a></li>
                    <li><a href="javascript:void(0)" class="submenusel">*Mountaineerig</a></li>
                    <li><a href="javascript:void(0)">*Walking</a></li>
                    <li><a href="javascript:void(0)">*Horse riding</a></li>
                    <li><a href="javascript:void(0)">*Camel riding</a></li>
                    <li><a href="javascript:void(0)">*Biking</a></li>
                    <li><a href="javascript:void(0)">*Film making</a></li>
                    <li><a href="javascript:void(0)">*Jeep sarari</a></li>
                </ul>
            </div>
        </div>

        <div class="right-basicmenu">
            <a href="javascript:void(0);">Culture Tours</a>
            <div class="right-submenu">
                <ul class="style">
                    <li><a href="javascript:void(0)">*Fishing</a></li>
                    <li><a href="javascript:void(0)">*Mountaineerig</a></li>
                </ul>
            </div>
        </div>
    </div>
  
    <script type="text/javascript">
        function clickon(){  
            var $p = $(this).parent();
            var iam = false;
            $('#right-menu .right-basicmenu').filter(function(){
                return $(this).data("clicked");
            }).each(function () {  
                if ($(this).data("clicked")) {
                    $(this).data("clicked",false);
                    $($(this).children().get(1)).slideUp("slow");
                    iam = $(this).data("index")==$p.data("index");
                }
            });
            if (!iam) {
                $p.data("clicked",!$p.data("clicked"));
                if($p.data("clicked"))
                    $(this).next().slideDown("slow");
                else
                    $(this).next().slideUp("slow");
            }
        }      
        $('#right-menu .right-basicmenu').each(function(i){
            $(this).data("clicked",false);
            $(this).data("index",i);
            var $a = $($(this).children().get(0));          
            $a.click(clickon);
            $a.next().slideUp("fast");
        });          
    </script>
</body>
</html>

Wednesday, August 27, 2014

web chat example on 8080 port using node.js

chat server app.js

//npm install socket.io --msvs_version=2012
var io = require('socket.io')(8080);

io.sockets.on('connection', function (socket) {
    console.log('Client connected...');
    //socket.emit('accepted', { hello: 'client!' });
    socket.on('join', function (data) {
        socket.nickname = data.name;
        console.log('nickname is ' + data.name);       
    });
    socket.on('messages', function (data) {
        console.log(data);
        socket.broadcast.emit('messages', data);
    });
});


chat client index.html


<html>
<head>
    <title>boroo</title>
    <style>
    #chat_body{display:block;height:300px;background:#efefef;}
    .chat-form{display:block;height:50px;border:1px solid #ccc;}
    </style>
</head>
<body>
<div id='chat_body'>
   
</div>
<hr>
<div class='chat-form'>
    <script src="jquery-1.11.1.min.js"></script>
    <script src="socket.io-1.0.6.js"></script>
    <form id='chat_form'>
        <input type='text' id='chat_input' size="50">
        <input type='submit' value='Send'>
    </form>
    <script>
        var nickname = '';
        var socket = io.connect('http://localhost:8080');
        socket.on('connect', function (data) {
            if (typeof socket.nickname == 'undefined') {
                socket.nickname = prompt("What is your nickname!");
                socket.emit('join', { name: socket.nickname });
            }
        });
        socket.on('messages', function (data) {
            var line = "<b>" + data.name + ": " + data.message + "</b>";
            var div = $('<div>').html(line);
            $("#chat_body").append(div);
        });
        $('#chat_form').submit(function(e) {
            var msg = $('#chat_input').val();
            var line = socket.nickname + ": " + msg;
            var div = $('<div>').html(line);
            $("#chat_body").append(div);
            $('#chat_input').val('');
            socket.emit('messages', { name: socket.nickname, message: msg });
            return false;
        });
    </script>
</div>
</body>
</html>

Tuesday, August 26, 2014

Correct way to Load JS Files With HTML files through NodeJS

NodeJS Serving the Page
var http = require('http'),
fs = require('fs');

fs.readFile(__dirname+'/default.htm', function (err, html) {
    if (err) {
        throw err; 
    }       
    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(port.number);
});
Default.html Page
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="objects/css/site.css" type="text/css" />
    <script src="objects/js/jquery.min.js" type="text/javascript"></script>
    <script src="objects/js/site.min.js" type="text/javascript"></script>
</head>

<body></body>    

</html>

web client make with custom module using node.js

make_request.js


var http = require('http');
exports.makeRequest = function(message){
    var options = {
        host: 'localhost', port: 8080, path: '/', method: 'post'
    };

    callback = function(response){
        var str = '';

        //another chunk of data has been recieved, so append it to `str`
        response.on('data', function (chunk) {
            str += chunk;
        });

        //the whole response has been recieved, so we just print it out here
        response.on('end', function(){
            console.log(str);
        });
    };

    var request = http.request(options, callback);
    request.write(message);
    request.end();
};


usage


var mr = require('./make_request.js');
mr.makeRequest("GET_HTML");
//client is request.write();

web server make with post, get request and multipart/form-data using Node.js

http_server.js


//npm install -g formidable
var formidable = require('formidable'),
sys = require('sys'),
http = require('http'),
util = require('util'),
url = require('url'),
qs = require('querystring');

http.createServer(function(request, response){
    if (request.url == '/upload' && request.method.toLowerCase() == 'post') {
        var body = '';
        request.on('data', function(data){
            body += data;
        });
        request.on('end', function(){
            //var jobj =  json.parse(body);
            //console.log(jobj.title);
            //var post =  qs.parse(body);           
        });
       
        // Instantiate a new formidable form for processing.
        var form = new formidable.IncomingForm();
       
        // form.parse analyzes the incoming stream data, picking apart the different fields and files for you.
        form.parse(request, function(err, fields, files) {
            if (err) {
                // Check for and handle any errors here.
                console.error(err.message);
                return;
            }
            response.writeHead(200, {'content-type': 'text/plain'});
            response.write('Received Upload:\n\n');
           
            // This last line responds to the form submission with a list of the parsed data and files.
            response.end(util.inspect({fields: fields, files: files}));
        });
        return;
    }
    else if(request.method == 'GET') {
        var url_parts = url.parse(request.url, true);
        console.log(url_parts.query);
    }
   
    // If this is a regular request, and not a form submission, then send the form.
    response.writeHead(200, {'content-type': 'text/html'});
    response.end(
        '<form action="/upload" enctype="multipart/form-data" method="post">'+
        '<label>title:</label><input type="text" name="title"><br>'+
        '<label>file:</label><input type="file" name="files" multiple="multiple"><br>'+
        '<input type="submit" value="Upload">'+
        '</form>'
    );
}).listen(8080);
//server is response.write();


result


upload file through http server with request, response using node.js

1. install node-v0.10.31-x86.msi

2. save sample.js

var http = require('http');
var fs = require('fs');

http.createServer(function (request, response) {
    var newFile = fs.createWriteStream("readme_copy.md");
    var fileBytes = request.headers['content-length'];
    var uploadedBytes = 0;
   
    request.pipe(newFile);
   
    request.on('data', function(chunk) {
        uploadedBytes += chunk.length;
        var progress = (uploadedBytes / fileBytes) * 100;
        response.write("progress: " + parseInt(progress, 10) + "%\n");
    });
   
    request.on('end', function() {
        response.end('Uploaded!');
    });
}).listen(8080);
console.log("Listening on port 8080...");

3. open command prompt, write "node sample.js" then enter to run js file on jvm

4. install Git-1.9.4-preview20140815.exe

5. run "Git Bash.exe" as "C:\Program Files (x86)\Git\bin\sh.exe" --login -i

6. white "curl --upload-file readme.md http://localhost:8080" then enter to upload file through http server


result