Saturday 5 October 2013

How to install ruby in rails alongside wampserver

Twitter Demo [PHP and javascript]

Twitter Demo [PHP and javascript]

htttp://dev.artoonsolutions.com/demo/twitter
htttp://dev.artoonsolutions.com/demo/twitter/javascript.php // for javascript reference

** inside this folder you will find javscript.php file this file help you to fetch some unauthorized data from twitter server
** Othere files inside in this folder for php oauth twitter referrence.

NOTE : [ Twitter still not providing oauth with javascript, so please do not waste time to find this kind of googling.]

STEPS :
1) Go to developer.twitter.com and create your own application.
2) At creation step of twitter you must have to provide callback url. [currently we have callback.php]
3) After application created you have to put application and secret key inside the code.

Facebook php demo and facebook javascript demo

Facebook php demo and facebook javascript demo

Please read first from this URL : http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/

Demo code is here :
http://dev.artoonsolutions.com/demo/facebook

1) Go to developer.facebook.com
2) Then create your facebook application with demo URL detail.
3) Grab your application key and secret key from application that you created. and put into fbmain.php file.
4) You can also test with javascript authentication detail. Look at url
http://dev.artoonso lutions.com/demo/facebook/javascript.php

NOTE : [Facebook is providing javscript and php Oauth 2.0 support.]

linkedin php demo and linkedin javascript demo

linkedin php demo and also linkedin javascript demo


Login and Register Script with Linkedin API and Javascript

Login and Register Script with Linkedin API and Javascript

Linkedin is the topmost social network for professionals. In this article I have explained how to use the Linkedin JavaScript API to access and use the user details from Linkedin. Linkedin provides a very beautiful API for developers to fetch the user details. We can use these details for a number of purpose on our web pages like login/register using Linkedin, showing user details from Linkedin, form autofills etc.

For registering the new application, go to Linkedin developers Page. Here you will get a from to fill, fill it as follows:



Now you will get the API key and secret for your application:

Adding Linkedin framework to page

<script type="text/javascript" src="http://platform.linkedin.com/in.js">
 api_key: lg2s1jdk6lfv //your application key
 onLoad: onLinkedInLoad //function to be called on JS framework load (optional)
 authorize: true   //true will detect if the user is logged in already (optional)
</script>

Add a Sign in with LinkedIn button

Adding Linkedin JS framework will give access to various user variables on our page. We can access these variables as <?js= firstName ?>. The following code will add the 'Linkedin Login' button on our page. After successful login, the button will be replaced by the message written in the script and the JS variables will be replaced by there actual values.
<script type="in/Login">
 Welcome, <?js= firstName ?> <?js= lastName ?>.
 </script>

Autofill Login form LinkedIn

Linkedin can fill details in the login/register form on our web pages. For this it provides a specific script tag of "IN/Login" type. See the following code:
<script type="IN/Login"> 
 <form method="post" action="register.html">
 <table>
  <tr>
   <td>First Name:</td><td><input type="text" name="first_name" value="<?js= firstName ?>" /></td>
  </tr>
  <tr>
   <td>Last Name:</td><td><input type="text" name="last_name" value="<?js= lastName ?>" /></td>
  </tr>
  <tr>
   <td>Password:</td><td><input type="password" name="pwd" value="" /></td>
  </tr>
  <tr>
   <td colspan="2"><input type="submit" value="Register" /></td>
  </tr>
 </table>
 </form>
</script>

Using Callback on LinkedIn JS load

<script type="text/javascript">
// 1. Runs when the JavaScript framework is loaded
function onLinkedInLoad() {
 IN.Event.on(IN, "auth", onLinkedInAuth);
}

// 2. Runs when the viewer has authenticated
function onLinkedInAuth() {
 IN.API.Profile("me").result(displayProfiles);
}

// 3. Runs when the Profile() API call returns successfully
// Insert user variables in the HTML
function displayProfiles(profiles) {
 member = profiles.values[0];
 document.getElementById('demo').style.display = 'block';
 var profile = "<p class='name' id=\"" + member.id + "\">" +  member.firstName + " " + member.lastName + "</p>";
 profile += '<p class="headline">'+member.headline+'</p>';
 document.getElementById("profiles").innerHTML = profile;
 document.getElementById("picture").innerHTML = '<img src="'+member.pictureUrl+'" class="image" />';
}
</script>

Complete Script

<html>
<head>
<title>WebSPeaks.in | LinkedIn API Usage<title>
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
 api_key: lg2s1jdk6lfv
 onLoad: onLinkedInLoad
 authorize: true
</script>
<script type="text/javascript">
// 1. Runs when the JavaScript framework is loaded
function onLinkedInLoad() {
 IN.Event.on(IN, "auth", onLinkedInAuth);
}

// 2. Runs when the viewer has authenticated
function onLinkedInAuth() {
 IN.API.Profile("me").result(displayProfiles);
}

// 3. Runs when the Profile() API call returns successfully
function displayProfiles(profiles) {
 member = profiles.values[0];
 document.getElementById('demo').style.display = 'block';
 var profile = "<p class='name' id=\"" + member.id + "\">" +  member.firstName + " " + member.lastName + "</p>";
 profile += '<p class="headline">'+member.headline+'</p>';
 document.getElementById("profiles").innerHTML = profile;
 document.getElementById("picture").innerHTML = '<img src="'+member.pictureUrl+'" class="image" />';
}
</script>
</head>
<body>
<div id="main">
 <h4>JS template method</h4>
 <script type="in/Login">
  <div class="data">
   <div class="picture">
    <img alt="<?js= headline ?>" src="<?js= pictureUrl ?>" class="image" />
   </div>
   <div class="profiles">
    <p class='name'><?js= firstName ?> <?js= lastName ?></p>
    <p class="headline"><?js= headline ?></p>
   </div>
  </div>
 </script>

 <div id="demo">
  <h4>Dom insertion method</h4>
  <div class="data">
   <div id="picture" class="picture"></div>
   <div id="profiles" class="profiles"></div>
  </div>
 </div>

 <div id="form">
  <h4>Register/Login Form Autofill</h4>
  <script type="IN/Login"> 
   <form method="post">
   <input type="hidden" name="linkedin-id" value="<?js= id ?>" />
   <table>
    <tr>
     <td>First Name:</td><td><input type="text" name="first_name" value="<?js= firstName ?>" /></td>
    </tr>
    <tr>
     <td>Last Name:</td><td><input type="text" name="last_name" value="<?js= lastName ?>" /></td>
    </tr>
    <tr>
     <td>Password:</td><td><input type="password" name="pwd" value="" /></td>
    </tr>
    <tr>
     <td colspan="2"><input type="submit" value="Register" /></td>
    </tr>
   </table>
   </form>
  </script>
 </div>
</div>
</body>
</html>

Register/login.php

<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$pwd = $_POST['pwd'];
$linkedin_id = $_POST['linkedin-id'];

//write mysql insert logic dor registration
//or
//write mysql logic for login
?>

CSS Code

body {
 font-family:Helvetica,"Nimbus Sans L",sans-serif;
}
#main{
    -moz-box-align: center;
    -moz-box-orient: vertical;
    border: 0.5em solid #E3E9FF;
    display: block;
    height: auto;
    margin: auto;
    padding: 10px;
    text-overflow: ellipsis;
    width: 350px;
    word-wrap: break-word;
}
.data{
 background-color: #e3e3e3;
    height: 88px;
    padding: 5px;
 margin-bottom:20px;
}
.image{
 border: 1px solid #ffffff;
 padding:3px;
}
.picture{
 float:left;
 width:90px;
}
.profiles{
 float:left;
 width:225px;
 padding: 0 0 0 10px;
}
p.name{
 color:#069;
 font-weight:bold;
 margin:0;
}
p.headline{
 font-size:12px;
}
#demo{
 display:none;
}

die ajax request - best habit for auto search

die ajax request - best habit for auto search

var ajax_request;
function do_something()
{
if(typeof ajax_request !== "undefined")
ajax_request.abort();

ajax_request = $.ajax({
-----------------
-----------
--

simple login page using PHP and MongoDB.

simple login page using PHP and MongoDB.


Installation

Windows
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/

You can download PHP mongo drive/extension dll file from following URL https://github.com/mongodb/mongo-php-driver/downloads. Copy php_mongo.dll file into your PHP extension directory

Linux & Mac
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

Connecting into MongoDB
PHP code connecting with out Authentication.
<?php
$mongo = new Mongo();
$db = $mongo->selectDB(“test”);
?>

With Authentication
<?php
$mongo = new Mongo(“mongodb://{$username}:{$password}@{$host}”);
$db = $mongo->selectDB(“test”);
?>

By default MongoDB contains sample database called “test”.

Creating New Database
$db = $mongo->Database_Name;

Note: Technically, you don't need to manually create databases in MongoDB due to its schemaless "lazy" way of creating databases.

Queries
PHP code to get MongoDB databases.
//Get list of databases
$mongo->admin->command(array(“listDatabases” => 1));
//Get list of Collections in test db
$db->listCollections();

Mongo Shell/Terminal/Command Prompt
db.listDatabases
db.test.showCollections

Create Collection(table)
You can created a collection/table but executing following code.
$db->createCollection(“people”,false);

Note: here false referred to unlimitted size, if you give true you have to mention the size of maximum.

Mongo Shell
db.createCollection(“people”,false);

Insert Record
Insert records int MongoDB.
<?php
$people = $db->people;
$insert = array(“user” => “demo@9lessons.info”, “password” => md5(“demo_password”));
$db->insert($insert);
?>

Mongo Shell:
db.people.insert({user:”user_name”,password:”password”});

Update Records
Update records into MongoDB
<?php
$update = array(“$set” => array(“user” => “demo@9lessons.info”));
$where = array(“password” => “password”);
$people->update($where,$update);
?>

Mongo Shell:
db.people.update({password:”password”},{$set : {user:”demo@demo.com”}});

HTML Code
<form action="index.php" method="POST">
Email:
<input type="text" id="usr_email" name="usr_email"  />
Password:
<input type="password" id="usr_password" name="usr_password" />  
<input  name="submitForm" id="submitForm" type="submit" value="Login" />
</form>

PHP Code
<?php
$succss = "";
if(isset($_POST) and $_POST['submitForm'] == "Login" )
{
$usr_email = mysql_escape_string($_POST['usr_email']);
$usr_password = mysql_escape_string($_POST['usr_password']);
$error = array();
// Email Validation
if(empty($usr_email) or !filter_var($usr_email,FILTER_SANITIZE_EMAIL))
{
$error[] = "Empty or invalid email address";
}
if(empty($usr_password)){
$error[] = "Enter your password";
}
if(count($error) == 0){
$con = new Mongo();
if($con){
// Select Database
$db = $con->test;
// Select Collection
$people = $db->people;
$qry = array("user" => $usr_email,"password" => md5($usr_password));
$result = $people->findOne($qry);
if($result){
$success = "You are successully loggedIn";
// Rest of code up to you....
}
} else {
die("Mongo DB not installed");
}
}
}
?>

highlight word in php

highlight word in php


PHP coding tips for Performance Improvement devloper must see

PHP coding tips for Performance Improvement devloper must see


Mssql pagination query

Mssql pagination query

$sql="SELECT * FROM(
SELECT row_number() OVER (ORDER BY TransactionID) AS No, p.*
FROM payflow_reporting p
$where_filter
) AS A
WHERE A.No BETWEEN (?) AND (?)";

$query=$this->db->query($sql, array( $offset, $limit));
return $query->result();

Make ajax call using core javascript

Make ajax call using core javascript

ref url http://stackoverflow.com/questions/3946446/why-is-my-code-failing-to-pass-parameters-from-javascript-to-jsp-using-xmlhttpre

For passind data using post use following code
var myVar1 = encodeURIComponent("c6c684d9cc99476a7e7e853d77540ceb");
xhr.open("POST", "http://csce:8080/test/index.jsp", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("id=" + myVar1);

find distance from latitude and longitude with mysql

find distance from latitude and longitude with mysql

$radius = 1;
$my_lat = 21.21586;
$my_long = 72.86315;

//3959 for miles and 6371 for km
$res = mysql_query("SELECT *, ( 3959 * acos( cos( radians('$my_lat') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('$my_long') ) + sin( radians('$my_lat') ) * sin( radians( latitude ) ) ) ) AS distance FROM map_point HAVING distance < '$radius' ORDER BY distance");

returns data from 1 mile radius from given $my_lat and $my_long

Get tweets from twitter account with php

Get tweets from twitter account with php


Get Follower List of twitter

Get Follower List of twitter

file_get_contents("https://api.twitter.com/1/followers/ids.json?screen_name='SCREEN NAME'&cursor=-1");

chart using jquery ajax

chart using jquery ajax


http://demo.tutorialzine.com/2013/01/charts-jquery-ajax/

Working with new php date and timePost title


     Working with Dates and Times prior to PHP 5.2 meant using date(), strtotime(), and other date related functions sometimes in convoluted ways to get to the date(s) you were looking for. Fortunately with PHP 5.2 the DateTime() class were introduced. (DateTimeZone() was introduced as well but is not covered here). It was further enhanced in PHP with additionally methods as well as the new DatePeriod() and DateInterval() classes.

Getting Started

Before we get started I will link to the relevant pages in the PHP manual for the classes that we will be using here. All of these require running PHP 5.2 or newer. Make sure you check your version of PHP before using any of this code.
Also, keep in mind that when using DateTime(), when passing a Unix Timestamp as a parameter requires prepending an @ to the timestamp for it be recognized as a timestamp.
1
$datetime = new DateTime('@123457890');

Getting the difference between two dates

1
2
3
4
5
6
$datetime1 = new DateTime();
$datetime2 = new DateTime('2013-01-03 17:13:00');
$interval  = $datetime1->diff($datetime2);
$elapsed   = $interval->format('%y years, %m months, %a days, 
                                %h hours, %i minutes, %S seconds');
echo $elapsed;
See it in action
If you want to eliminate any periods that have zero values you can use the snippet below to remove them.
1
2
3
4
5
6
7
8
9
$elapsed = $interval->format('%y years, %m months, %d days, 
                              %h hours, %i minutes');
$elapsed = str_replace(array('0 years,', ' 0 months,', ' 0 days,', 
                            ' 0 hours,', ' 0 minutes,'), '', $elapsed);
$elapsed = str_replace(array('1 years, ', ' 1 months, ', ' 1 days, ', 
                             ' 1 hours, ', ' 1 minutes'), array('1 year, ', 
                             '1 month, ', ' 1 day, ', ' 1 hour, ', ' 1 minute'), 
                       $elapsed);
echo $elapsed;
See it in action

Birthdays/calculate age

1
2
3
4
$today     = new DateTime();
$birthdate = new DateTime("1973-04-18");
$interval  = $today->diff($birthdate);
echo $interval->format('%y years');
See it in action

Adding period of time to a date

For PHP 5.3 or newer
1
2
3
$datetime = new DateTime();
$datetime->add(new DateInterval('P6M'));
echo $datetime->format('Y-m-d');
See it in action
For PHP 5.2
1
2
3
$datetime = new DateTime();
$datetime->modify('+6 months');
echo $datetime->format('Y-m-d');
See it in action

Start date for a given week

1
2
3
4
$start_date  = new DateTime("2013-05-13");
$day_of_week = $start_date->format("w");
$start_date->modify('-' . $day_of_week . ' day');
echo $start_date->format('l, F jS, Y');
See it in action

Looping through the days between two dates

For PHP 5.3 or newer
1
2
3
4
5
6
7
8
9
$start    = new DateTime('2013-02-01');
$end      = new DateTime('2013-02-17');
$interval = new DateInterval('P1D');
$period   = new DatePeriod($start, $interval, $end);
 
foreach ($period as $dt)
{
    echo $dt->format("l Y-m-d") . PHP_EOL;
}
See it in action
An alternative way to do this using DateInterval::createFromDateString()
1
2
3
4
5
6
7
8
9
$start    = new DateTime('2013-02-01');
$end      = new DateTime('2013-02-17');
$interval = DateInterval::createFromDateString('1 day');
$period   = new DatePeriod($start, $interval, $end);
 
foreach ($period as $dt)
{
    echo $dt->format("l Y-m-d") . PHP_EOL;
}
See it in action
For PHP 5.2
1
2
3
4
5
6
7
$start = new DateTime('2013-02-01');
$end   = new DateTime('2013-02-17');
while ($start < = $end)
{
    echo $start->format("m/d/Y") . PHP_EOL;
    $start->modify("+1 day");
}
See it in action

List all days in a month

1
2
3
4
5
6
7
8
9
$start    = new DateTime('first day of this month');
$end      = new DateTime('first day of next month');
$interval = DateInterval::createFromDateString('1 day');
$period   = new DatePeriod($start, $interval, $end);
 
foreach ($period as $dt)
{
    echo $dt->format("l Y-m-d") . PHP_EOL;
}
See it in action
For PHP 5.2
1
2
3
4
5
6
7
$start = new DateTime('2013-01-31');
$end   = new DateTime('2013-02-05');
while($start < = $end)
{
    echo $start->format("m/d/Y"). PHP_EOL;
    $start->modify("+1 day");
}
See it in action

Get first day of the month

1
2
$datetime = new DateTime('first day of this month');
echo $datetime->format('jS, F Y');
See it in action

Get last day of the month

1
2
$datetime = new DateTime();
echo $datetime->format('Y-m-t');
See it in action
1
2
$datetime = new DateTime('last day of this month');
echo $datetime->format('F jS');
See it in action

Getting tomorrows date

1
2
$datetime = new DateTime('tomorrow');
echo $datetime->format('Y-m-d');
See it in action
Or alternatively
1
2
3
$datetime = new DateTime();
$datetime->add(new DateInterval("P1D"));
echo $datetime->format('Y-m-d');
See it in action
For PHP 5.2
1
2
3
$datetime = new DateTime();
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d');
See it in action

Compare dates & times

1
2
3
4
5
6
7
8
9
10
$date1 = DateTime::createFromFormat('H:i', '08:00');
$date2 = new DateTime();
if ($date1 > $date2)
{
    echo 'It is after 08:00';
}
else
{
    echo 'It is not after 08:00';
}

PHP Dropbox API

- This API authenticate dropbox user and get tokens from there which can be used anytime.
- Also i have created sample form file to test most of API.
It is at below url :
http://dev.artoonsolutions.com/phpDemo/DropBox-API

create custome hook

create custome hook


// referrece link : http://codeigniter.com/user_guide/general/hooks.html
class customHook extends CI_Hooks{
public $CI;
function __construct()
{
parent::__construct();
$this->CI = get_instance();
}
/*
+++++++++++++++++++++++++++++++++++++++++++++
This function will detect admin url and
check for session, if session null then
check for cookie, if cookie exist then
take username from it work ahead.
+++++++++++++++++++++++++++++++++++++++++++++
*/
function adminAutoLogin()
{
//check for admin url access or not
if($this->CI->router->directory == 'admin/')
{
//checking for admin session.
if(!$this->CI->session->userdata('admin_id') && $this->CI->input->cookie('bsgp_admin') != ''):
$this->CI->encrypt->set_cipher(MCRYPT_GOST); // set encryption type
$admin = $this->CI->encrypt->decode($this->CI->input->cookie('bsgp_admin')); // decode cookie value
if(is_string($admin)):
$admin_info = $this->CI->db->select('admin_id,username as admin_user', FALSE)->where('username',$admin)->get('bsgp_admins')->row_array();
$this->CI->session->set_userdata($admin_info);
endif;
elseif(!$this->CI->session->userdata('admin_id')):
$this->_setReferrer();
if($this->CI->router->class == 'login' && $this->CI->router->method != 'index')
redirect('admin/login');
else if($this->CI->router->class != 'login')
redirect('admin/login');
endif;
}
}
/*
+++++++++++++++++++++++++++++++++++++++++++
setting referrring url. user will redirect
this url after successfull login
+++++++++++++++++++++++++++++++++++++++++++
*/
private function _setReferrer()
{
if(isset($_SERVER['REDIRECT_QUERY_STRING']))
{
if(($this->CI->uri->rsegment('1') == 'login' && $this->CI->uri->rsegment('2') != 'index') || $this->CI->uri->rsegment('1') != 'login')
setFlashMessage('referrer',$_SERVER['REDIRECT_QUERY_STRING']);

}
}
}

create common database helper with all database query

create common database helper with all database query


/* dbug data*/
function dbug($data = ''){
echo '';
}
/*
+-----------------------------------------+
This Function will Save and Update data.
@params : $id -> get id
$data -> array of data
$table -> table name
$tableId -> table field name
+-----------------------------------------+
*/
function saveData($id ='', $data, $table, $tableId)
{
$CI =& get_instance();
if($id == "")
{
$CI->db->insert($table,$data);
$insert_id = $CI->db->insert_id();
if(check_db_column($table,'sort_order')){ //if sort_order field
$temp['sort_order']=$insert_id;
saveData($insert_id,$temp,$table,$tableId);
}
return $insert_id;
}
else
{
$CI->db->where($tableId,$id);
$CI->db->limit(1);
$CI->db->update($table,$data);
}
}
/*
+++++++++++++++++++++++++++++++++++++++++++++++++++++
This function will check column exist in database
or not? if column exist then return true otherwise
return false.

@params : $table_name -> name of the table
$column_name -> Column name you want to
check in table.
@return : TRUE OR FALSE
+++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
function check_db_column($table_name,$column_name)
{
$CI = & get_instance();

$sql = "SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = '".$CI->db->database."'
AND TABLE_NAME = '".$table_name."'
AND COLUMN_NAME = '".$column_name."'";

$rows = $CI->db->query($sql)->num_rows();
if($rows > 0)
return true;
else
return false;
}
/*
+-----------------------------------------+
This Function will Delete data.
@params : $id -> get id
$del_in -> 1 or 0 value change in db for delete purpose
$table -> table name
$tableId -> table field name
+-----------------------------------------+
*/
function deleteData($id, $del_in, $table, $tableId)
{
$CI =& get_instance();
$update['del_in'] = $del_in;
$CI->db->where($tableId,$id);
$CI->db->limit(1);
$CI->db->update($table,$update);
}
/*
+-----------------------------------------+
This Function will Edit form data.
@params : $id -> get id
$table -> table name
$tableId -> table field name
+-----------------------------------------+
*/
function formData($id, $table, $tableId)
{
$CI =& get_instance();
$CI->db->where($tableId, $id);
$CI->db->limit(1);
return $CI->db->get($table)->row_array();
}
/*
+-----------------------------------------+
This Function will return for find minimum ordering data.
@params : $start_id -> start row id
$end_id -> end row id
$table -> table name
$tableId -> table field name
+-----------------------------------------+
*/
function minOrderId($start_id, $end_id, $table, $tableId)
{
$CI =& get_instance();
$sql = 'SELECT min(`display_order`) as display_order
FROM '.$table.'
WHERE '.$tableId.' BETWEEN '.$start_id .' AND '.$end_id;
return $CI->db->query($sql);
}
/*
+-----------------------------------------+
This Function will return for update ordering data.
@params : $recordId -> field row id
$order -> order id
$table -> table name
$tableId -> table field name
+-----------------------------------------+
*/
function updateDisplayOrder($recordId, $order, $table, $tableId)
{
$CI =& get_instance();
$sql = 'UPDATE '.$table.'
SET `display_order`='.$order.'
WHERE `del_in`=0 AND '.$tableId.' = '.$recordId;
return $CI->db->query($sql);
}
/*
+-----------------------------------------+
This Function will return for check field data.
@params : $whereData -> condition field name
$dbTable -> table name
+-----------------------------------------+
*/
function checkField($whereData, $dbTable)
{
$CI =& get_instance();
if($whereData)
$CI->db->where($whereData);
return $CI->db->get($dbTable);
}
/*
+-----------------------------------------+
This Function will return for config value.
@params : $keyWord -> config keyword
$dbTable -> table name
+-----------------------------------------+
*/
function getConfig($keyWord,$dbTable)
{
$C =& get_instance();
$C->db->select('config_value');
$C->db->where('config_keyword',$keyWord);
$response = $C->db->get($dbTable)->row_array();
return $response['config_value'];
}
/*
+------------------------------------------------------------------+
Function will be use for single field value.
Input ->
@params-> $field : Name of field you want to fetch.
$table : Name of table
$wh : Where condition field name
$cond : condition operator value.
+------------------------------------------------------------------+
*/
function getField($field,$table,$wh ='',$cond='')
{
$CI = & get_instance();

$CI->db->select($field,FALSE);
if($wh && $cond)
$CI->db->where($wh,$cond)->limit(1);

$res = $CI->db->get($table);

//if we want some aggreagration then we pass field name in $wh
$result =$res->row_array();
unset($CI);
//echo $result['new_order'];die;
return $result[$field];
}
/*
+------------------------------------------------------------------+
Function will be use for listing all value.
@params-> $table : Name of table
+------------------------------------------------------------------+
*/
function getDbTableData($table)
{
$CI =& get_instance();
$CI->db->where('del_in',0);
return $CI->db->get($table)->result_array();
}
/*
+------------------------------------------------------------------+
Function will be use for generate random string.
@params-> $table : Name of table
+------------------------------------------------------------------+
*/
function get_random_string($table,$field_code)
{
// Create a random user id
$random_unique = random_string('alnum', 6);
// Make sure the random user_id isn't already in use
$CI = get_instance();
$CI->db->where($field_code, $random_unique);
$query = $CI->db->get_where($table);

if ($query->num_rows() > 0)
{
// If the random user_id is already in use, get a new number
$this->get_random_string();
}
return $random_unique;
}
/*
+------------------------------------------------------------------+
Function will return array which is usable for codeigniter
Form_dropdown function
@params-> $sql : Query to database
$keyField : Key field you want to get as value
$valueField : Option you want to make appear at dropdown
+------------------------------------------------------------------+
*/
function getDropDownAry($sql,$keyField,$valueField,$dropDown = array())
{
$CI =& get_instance();

$result = $CI->db->query($sql);
foreach($result->result_array() as $res)
{
$key = $res[$keyField];
$dropDown[$key] = $res[$valueField];
}
return $dropDown;
}
/*
+------------------------------------------------------------------+
Function will be use for student score wise grade.
@params-> $score : number of score
+------------------------------------------------------------------+
*/
function getGradeName($score)
{
$CI =& get_instance();
$CI->db->where("grade_from <= ".$score." and grade_to >= ".$score);
$response = $CI->db->get('grade')->row_array();
return $response['grade_name'];
}
/*
+------------------------------------------------------------------+
Function will be use for taluko name.
@params-> $Id : taluko id
+------------------------------------------------------------------+
*/
function gTaluko($Id='')
{
return getField('taluko_name', 'taluko', 'taluko_id', $Id);
}
/*
+------------------------------------------------------------------+
Function will be use for district name.
@params-> $Id : district id
+------------------------------------------------------------------+
*/
function gDistrict($Id='')
{
return getField('district_name', 'district', 'district_id', $Id);
}
/*
+------------------------------------------------------------------+
Function will be use for state name.
@params-> $Id : state id
+------------------------------------------------------------------+
*/
function gState($Id='')
{
return getField('state_name', 'state', 'state_id', $Id);
}
?>

File upload in codeiginter

File upload in codeiginter


/*
+-----------------------------------------+
This Function will return file upload or not.
@params : $uploadFile -> input file name
$filetype -> file type parameter eg. img, doc..
$folder -> upload folder path name
$fileName -> file name
+-----------------------------------------+
*/
function uploadFile($uploadFile, $filetype, $folder, $watermark=false, $fileName='')
{
$resultArr = array();

$config['max_size'] = '1024000';
if($filetype == 'img') $config['allowed_types'] = 'gif|jpg|png|jpeg|JPEG';
if($filetype == 'All') $config['allowed_types'] = '*';
if($filetype == 'pdf') $config['allowed_types'] = 'pdf';
if($filetype == 'doc') $config['allowed_types'] = 'pdf|doc|docx|xls|ppt|rtf|xlsx|pptx|swf|gif|jpg|png|jpeg|txt|csv|text|TEXT|ACL|AFP|ANS|CSV|CWK|STW|RPT|PDAX|PAP|PAGES|SXW|STW|QUOX|WRI|XML|HTML|MCW|XPS|TXT|ABW|JPEG|PNG|SWF|PPT|PPTX|PDF|DOC|DOCX|XLS|XLSX|TeX';
if($filetype == 'csv') $config['allowed_types'] = 'csv';
if($filetype == 'swf') $config['allowed_types'] = 'swf';
if($filetype == 'video') $config['allowed_types'] = 'flv|mp4|mov';

$config['upload_path'] = $folder;
if($fileName != "")
$config['file_name'] = $fileName;

$this->load->library('upload', $config);
$this->upload->initialize($config);

if(!$this->upload->do_upload($uploadFile))
{
$resultArr['success'] = false;
$resultArr['error'] = $this->upload->display_errors();
}
else //if file upload
{
$resArr = $this->upload->data();
$fullname = $resArr['file_name'];

$resultArr['success'] = true;
$resultArr['path'] = $folder."/".$fullname;

if($watermark) //if watermark image
$this->watermark($fullname);
}
return $resultArr;
}

water mark in image

water mark in image


/*
+------------------------------------------------------------------+
Function will be use for excel download.
@params-> $fullname : name of the file
+------------------------------------------------------------------+
*/
function watermark($fullname)
{
$this->load->library('image_lib');
$configwater['image_library'] = 'gd2';
$configwater['wm_text'] = "FREE 2000544";
$configwater['wm_type'] = 'text';
$configwater['source_image'] = 'uploads/coupon/'.$fullname;
//$configwater['new_image'] = base_url() .'uploads/coupon/'. basename($configwater['source_image'],'.png') .'_watermark.png' ;
$configwater['wm_font_path']= 'system/fonts/texb.ttf';
$configwater['wm_font_size'] = '20';
$configwater['wm_vrt_alignment'] = 'bottom';
$configwater['wm_hor_alignment'] = 'center';

$this->image_lib->initialize($configwater);
$this->image_lib->watermark();
$this->image_lib->clear();
}

/*

file upload with ajaxPost title


/*
+------------------------------------------------------------------+
Function will be use for ajax uploading image.
@params-> $module : Name of module name for upload image
$fileType : Name of file type
$inputFile : Input file name
$watermark = false : if not watermark image
+------------------------------------------------------------------+
*/
function ajaxUploading($module, $fileType, $inputFile, $watermark=false)
{
//print_r($_FILES);die;
if($_FILES[$inputFile]["name"])
$new_file_name = alterFileName($_FILES[$inputFile]["name"]);
else
$new_file_name = '';

$data['type'] = $_FILES[$inputFile]["type"];
$folder = 'uploads/'.$module;
if(!file_exists($folder))
{
mkdir($folder,0777,true);
chmod($folder,0777);
}

$res = $this->mdl_common->uploadFile($inputFile, $fileType, $folder, $watermark, $new_file_name);

if($res['success'])
{
if($this->router->class == 'brochures')
{
$actual_image = $res["path"];
$thumb_path = load_thumb_image_nmd($actual_image);
resize_image($actual_image,$thumb_path,600,440);
}

$data['link'] = $res["path"];
$data['input'] = $inputFile;
return $this->load->view('admin/elements/ajax_view_image',$data,true);
}
else
{
$res['error'] = strip_tags($res['error']);
return $res;
}
}

delete Upload Image with ajax


/*
+------------------------------------------------------------------+
Function will be use for delete uploaded image.
@params-> $field : Name of input field name
$table : Name of table in db
$tableId : Name of field name in db
+------------------------------------------------------------------+
*/
function deleteUploaderImage($field, $table, $tableId)
{
//detect ajax request
if($this->input->is_ajax_request()):

//if in edit mode
if($this->input->post('auto_id') != '')
$image = $this->mdl_common->getField($field, $table, $tableId, $this->input->post('auto_id'));
else //simple in form functionality
$image = $this->input->post('path');

//remove image static ajax upload
if(substr_count($image,'./') > 0)
@unlink($image);
else
@unlink('./'.$image);

//thumb image remove
if($this->router->class == 'brochures')
{
$thumb_path = load_thumb_image_nmd($image);
@unlink($thumb_path);
}

//making this field null for edit reference
if($this->input->post('auto_id') != '')
$this->db->set($field,'')->where($tableId,$this->input->post('auto_id'))->update($table);

endif;

}

export excel file

export excel file


/* +------------------------------------------------------------------+ Function will be use for generate export excel file. @params-> $fileName : download file name $columns : column field name in file $listArr : list data of array +------------------------------------------------------------------+ */ function exportExcel($fileName,$columns,$listArr) { $this->load->helper('download'); $handle1 = fopen($fileName,'w'); $fileTextArray = array_values($columns); $fileText = implode("\t",$fileTextArray)."\n"; fwrite($handle1, $fileText); foreach($listArr as $list) { $fileText = implode("\t",$list)."\n"; fwrite($handle1, $fileText); } fclose($handle1); $this->force_download($fileName); unlink($fileName); } /* +------------------------------------------------------------------+ Function will be use for excel download. @params-> $file : download file name +------------------------------------------------------------------+ */ function force_download($file) { if ((isset($file))&&(file_exists($file))) { $fileName = str_replace("./","",$file); header("Content-length: ".filesize($file)); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.$fileName.'"'); readfile($file); } else echo "No file selected"; }