Showing posts from 2015

Get last inserted id in codeigniter

You get last_id like this function add_post($post_data){$this->db->insert('posts',$post_data);$insert_id =$this->db->insert_id();return$insert_id;}OR for Specific table you cannot use $this->db->insert_id() . even the last insert happened long ago it can be fetched like this. may be wrong. but working well for me $this->db->select_max('{primary key}'); $result= $this->db

Remove last comma from string in php

$string = "Bar, Restaurant, Take Away Food, Dive School, Hotel,"; rtrim($string, ","); or You can use substr($string, 0, -1);

How to set and get session in Codeigniter

you can set data to session simply like this in controller $this->load->library('session'); $this->session->set_userdata(array('user_id'=> $user->uid,'username'=> $user->username,'groupid'=> $user->groupid,'date'=> $user->date_cr,'serial'=> $user->serial,'rec_id'=> $user->rec_id,'status'=> TRUE )); and you can get session data like this: $u_rec_id = $this->session->userdata('rec_id'); $serial = $this->session->userdata(

Add http before url in php

function addhttp($url){if(!preg_match("~^(?:f|ht)tps?://~i", $url)){ $url ="http://". $url;}return $url;}

Remove specifc value from array using jQuery

var myarray = ["Banana", "Orange", "Apple", "Mango"];
myarray.splice( 'Orange',myarray) ,1 );
Result:  ["Banana", "Apple", "Mango";


arr = [1, 2, 3, 4, 5] // array inicialvar removeItem = 2;   // item do array que deverá ser removido

arr = jQuery.grep(arr, function(value) {
        return value != removeItem;

// new array
// [1, 3, 4, 5]

check value exists in array in jquery

var fruits = ["Banana", "Orange", "Apple", "Mango"];
if($.inArray('Orange',fruits)!=-1){ // Found It.}

Get image height and width when choose file using jquery

<script type="text/javascript">
  function readURLL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                var image = new Image();
                image.src =;
                image.onload = function () {
                    //Determine the Height and Width.
                    var height = this.height;
                    var width = this.width;
                    if (height > 100 || width > 100) {
                        alert("Height and Width must not exceed 100px.");
                        return false;
                    return true;

           var v=  reader.readAsDataURL(input.files[0]);
<img class="i…

get image ratio using php

$image='Aye-Myat.jpg';//Image Path
list($originalWidth, $originalHeight) = getimagesize($image);
$ratio = $originalWidth / $originalHeight;
$aspect_ratio = round($ratio,2);

Reset form after call ajax using jquery

Use jQuery
$("#form_id")[0].reset(); or in plain JavaScript: document.getElementById("cform").reset();

Reverse an array in php without using the reverse function

<?php $array = array(1, 2, 3, 4); $size = sizeof($array); for($i=$size-1; $i>=0; $i--){ echo $array[$i]; } ?>

sort array without using sort function in php

Here is the way of sorting.
<?php $array=array('2','4','8','5','1','7','6','9','10','3'); echo "Unsorted array is: "; echo "<br />"; print_r($array);for($j =0; $j < count($array); $j ++){for($i =0; $i < count($array)-1; $i ++){if($array[$i]> $array[$i+1]){ $temp = $array[$i+1]; $array[$i+1]=$array[$i]; $array[$i]=$temp;}}} echo "Sorted Array is: "; echo "<br />"; print_r($array);?>OR$array1 = array(1,5,2,25,3); for($i=0; $i<count($array1); $i++) { for($j=0; $j<count($array1); $j++) { if($array1[$j] > $array1[$i]) { $temp=$array1[$i]; $array1[$i] = $array1[$j]; $array1[$j] = $temp; } } } print_r($array1);

Delete confirmation dialog on href-link?

<ahref="delete.php?id=22"onclick="return confirm('Are you sure you want to delete this?')">Delete</a>

get string before a specified character in jquery

If you like it short simply use a RegExp:
var streetAddress =/[^,]*/.exec(addy)[0];OR Try Thisvar newString =string.substr(0,string.indexOf(','));

get url segment in codeigniter

This provides you to retrieve information from your URI strings
$this->uri->segment(n);// n=1 for controller, n=2 for method, etc consider this example
it will return
$this->uri->segment(1);// controller $this->uri->segment(2);// action $this->uri->segment(3);// 1stsegment $this->uri->segment(4);// 2ndsegment

add one array to another in php

use array_push()  to add one or more elements onto the end of array.  Example: <?php
$stack = array("orange", "banana");array_push($stack, "apple", "raspberry");print_r($stack);?>
The above example will output: Array ( [0] => orange [1] => banana [2] => apple [3] => raspberry )

session_id() regenerated on refresh in php

First of all, you set your session lifetime to 10 seconds, which means that you get a new session after every 10 seconds.
Side note: It's normal behaviour for some browsers to discard session cookies when closing the browser.
If you need your session to expand over multiple browser sessions, you need to use persistent cookies.
function init_session(/* ... */){if(!isset($_SESSION)){ session_start();}//Is it a running session?if(isset($_SESSION['somevalue'])){//Everything is fine, session is loaded, no need to reload from cookies}else{if(isset($_COOKIE['yourcookiename'])){//reload session from cookie}else{ create_session();}}}function create_session(){ $_SESSION['somevalue']=1;//setcookie}

how to set default timezone in codeigniter?

To resolve this issue you have to set default time zone in index.php of root directory


Difference Between mysql and mysqli?

“mysqli” extension is an improvement over the old “mysql” extension. In fact, the “i” in mysqli stands for “improved”.
mysqli was developed to take advantage of the new features available in MySQL since version 4.1.3. Also, you can use it since PHP 5. So, if you code with PHP5 with a newer version of MySQL, it’s strongly recommended for you to use the extension “mysqli” over “mysql”.
Key benefits of mysqli over mysql extension Object-oriented interface. You can still use the "old procedural" way of calling the mysql extension but the OO version groups the functions by their purpose.Prepared Statements. Those are useful to prevent SQL injections and are executed faster.Multiple Statements. With this "feature", you can execute multiple SQL queries inside only one "mysqli" call. This reduces the round trips between the database server and the PHP server.Support for Transactions. This is really useful to write robust applications. It gives you the …

Get Selected data from select2 and call ajax

$('#AdvertID').on("select2:select", function(e) {
            var selectedData = $('#AdvertID').select2('data')[0];// what you would like to happen
                    type: "POST",
                    url : "Your URL",
                    data: {id:'5',name:'test'},
                    catch: false,
                    success: function(data)

\r\n not working for new line in php

Try this:
echo str_replace(array("\r\n","\r","\n"),'<br>',$message);// or echo nl2br($message);

add button group using bootstrap

Bootstrap allows you to group a series of buttons together (on a single line) in a button group:
Use a <div> element with class .btn-group to create a button group:
<buttontype="button"class="btn btn-primary">Button 1</button>
<buttontype="button"class="btn btn-primary">Button 2</button>
<buttontype="button"class="btn btn-primary">Button 3</button>

How to add active class to codeigniter?

try this one.i think no need of javascript or jquery.
If you are using codeigniter then you can use URI Class.
<liclass="home"> <a class="<?php if($this->uri->segment(1)=="search"){echo "active";}?>" href="<?=base_url('search')?>"> <iclass="icon-search"></i><span>BEDRIJF ZOEKEN</span></a></li>

Write query in codeigniter view file

You could try this...
<?php $CI =& get_instance(); $query= $CI->webpages->get_where_custom('parent_id',0);foreach($query->result()as $row){ $query1=$CI->webpages->get_where_custom('parent_id',$row->id);foreach($query1->result()as $row1){ $row1->id;}}?> It's not according MVC rule but it's possible.
More details

Replace multiple characters from string in php

str_replace() can take an array, so you could do:
$new_str = str_replace(str_split('\\/:*?"<>|'),' ', $string); Alternatively you could use preg_replace():
$new_str = preg_replace('~[\\\\/:*?"<>|]~',' ', $string);or str_replace(array(':','\\','/','*'),' ', $string);

Fatal error: Call to undefined function base_url() in CodeIgniter

You have to load the url helper to access that function. Either you add $this->load->helper('url'); somewhere in your controller. Alternately, to have it be loaded automatically everywhere, make sure the line in application/config/autoload.php that looks like $autoload['helper']= array('url'); has 'url' in that array (as shown above).

Read More

Set language in codeigniter

First we need to configure the necessary files before we can start using language support. The CodeIgniter config file, located in the application/config directory, contains an option called language which defines the default language of the application.

$config['language'] = 'english';

First we need to configure the necessary files before we can start using language support. The CodeIgniter config file, located in the application/config directory, contains an option called language which defines the default language of the application.

$config['language'] = 'english';

We also need to create the actual files which contain our messages in different languages. These files need to be placed inside the application/language directory with a separate directory for each language. For example, English language files should reside in the application/language/english directory, and French language files should be located in application/language/french…

Remove index.php from url in codeigniter

Try It. Open config.php and do following replaces $config['index_page']="index.php" to $config['index_page']="" In some cases the default setting for uri_protocol does not work properly. Just replace $config['uri_protocol']="AUTO"by $config['uri_protocol']="REQUEST_URI" HTACCESS RewriteEngine on RewriteCond $1 !^(index\.php|resources|robots\.txt)RewriteCond%{REQUEST_FILENAME}!-f RewriteCond%{REQUEST_FILENAME}!-d RewriteRule^(.*)$ index.php/$1 [L,QSA] View More at Stack Overflow

How to move Prestashop from localhost to domain (or vice versa)

This article describes how to migrate Prestashop installation from your PC (localhost) to your domain. The reverce process is pretty much the same. On localhost I’m using XAMPP, which works well for Prestashop without setting any special parameters. Reference from premium-templates

1) Copy all files from from localhost to your FTP, usually into root folder or folder like “shop” 2) Backup database from localhost Login to phpMyadmin on localhost (http://localhost/phpmyadmin/), select your database to see all the tables. Click on export tab. You can use “Quick” method to export it as .sql file or choose “Custom” and export database as compresssed file (zipped, gzipped, bzipped). I recommend compress the database, so you can upload smaller file in next step.

3) Import database on hosting server Again, login to phpMyAdmin, select your database (usually you have to create it in administration of hosting account). Make sure your database has setup same collation (usually utf8_gener…

Error 404 - Can't access Admin after moving to new server

The reason for this error is that store_id and website_id for admin should be set to 0 (zero). But, when you import database to new server, somehow these values are not set to 0.
Open PhpMyAdmin and run the following query in your database:-
SET FOREIGN_KEY_CHECKS=0; UPDATE `core_store` SET store_id = 0 WHERE code='admin'; UPDATE `core_store_group` SET group_id = 0 WHERE name='Default'; UPDATE `core_website` SET website_id = 0 WHERE code='admin'; UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN'; SET FOREIGN_KEY_CHECKS=1; Back up database before making any changes also see log file to find exact issue. Also you can refer link 404 magento admin error Hope this is helpful to you

Get file extension from a path in Laravel

Use the File::extension() method.
$extension =File::extension($filename); If there is no extension, an empty string is returned. Otherwise, a string containing everything after the last period in the filename is returned.

Get all users session data in Codeigniter

to get all session data you can use $this->session->all_userdata(); to print all your session variable use this line anywhere in your code : echo '<pre>'; print_r($this->session->all_userdata());exit;

Add 1 month from today in php

$endOfCycle=date('Y-m-d', strtotime("+30 days"));or try this:
$endOfCycle = date("Y-m", time()+2592000); this adds 30 days, not exactly a month tough.

Create helper in codeigniter

A CodeIgniter helper is a PHP file with multiple functions. It is not a class
Create a file and put the following code into it.
<?php if(!defined('BASEPATH'))exit('No direct script access allowed');if(! function_exists('test_method')){function test_method($var =''){return $var;}} Save this to application/helpers/ . We shall call it "new_helper.php"
The first line exists to make sure the file cannot be included and ran from outside the CodeIgniter scope. Everything after this is self explanatory.

Using the Helper
This can be in your controller, model or view (not preferable)
$this->load->helper('new_helper'); echo test_method('Hello World'); If you use this helper in a lot of locations you can have it load automatically by adding it to the autoload configuration file.
$autoload['helper']= array('new_helper');

Select records from today, this week, this month php mysql

Assuming your date column is an actual MySQL date column:
SELECT * FROM jokes WHERE YEAR(date)= YEAR(NOW()) AND MONTH(date)=MONTH(NOW()); Current week:

Delete all numbers after point in PHP

floor() will round a number down to the nearest integer.
Using the explicit cast to (int) is the most efficient way to to this AFAIK. Also casting to (int) will cut off the digits after the "." if the number is negative instead of rounding to the next lower negative number:
echo (int)(-3.75);//echoes "-3"; echo floor(-3.75);//echoes "-4";

Stop Paypal recurring payment from paypal

Cancelling a subscription cancels all future scheduled payments of that subscription. A subscription can be cancelled up until three business days before the next scheduled payment.
1.Log in to your PayPal account.
2.Click Profile near the top of the page.
3.Click My money.
4.Click Update beside 'My pre-approved payments.'
5.Click the name of the subscription you wish to cancel.
6.Click Cancel.
this is from paypal documentation find it here

codeigniter active record left join

$this->db->select('email'); $this->db->from('emails');$this->db->where('user_id', $userid);$this->db->join('user_email','user_email.user_id =','left');$query = $this->db->get();