For smart Primates & ROBOTS (oh and ALIENS ).

Showing posts with label CodeIgniter. Show all posts
Showing posts with label CodeIgniter. Show all posts

Sunday, August 09, 2015

Unable to access an error message corresponding to your field name

Problem:

While working with CodeIgniter in-build set validation with text box for ex: invalid email or empty filed you may face this error "Unable to access an error message corresponding to your field name"

It means you have not set correctly error setup.
$this->form_validation->set_rules('blink', 'Link', 'required|trim|');
Share:

Monday, June 01, 2015

Parse XML in PHP with Attributes

Problem:
How to Parse XML in PHP with Attributes
Listed below the XML data.
Suppose you have a url which produce below XML data on request and you want to parse it in PHP including it's attribute for ex:  spell id="168839" minCount="1" maxCount="1" etc.

See below XML for full information:
<?xml version="1.0" encoding="utf-8"?>
<wowhead><item id="114811">
  <name>Hexweave Leggings</name>
  <level>640</level>
  <quality id="4">Epic</quality>
  <class id="4">Armor</class>
  <subclass id="1">Cloth Armor</subclass>
  <icon displayId="132245">inv_cloth_draenorcrafted_d_01pants</icon>
  <inventorySlot id="7">Legs</inventorySlot>
  <htmlTooltip>
    <table>
      <tr>
        <td><!--nstart-->
          <b class="q4">Hexweave Leggings</b>
          <!--nend--><!--ndstart--><!--ndend-->
          <span style="color: #ffd100">
            <br />
            Item Level<!--ilvl-->640</span>
          <br />
          <!--bo-->Binds when equipped
          <br />
          Unique-Equipped: Warlords Crafted (3)
          <table width="100%">
            <tr>
              <td>Legs</td>
              <th>Cloth</th>
            </tr>
          </table>
          <span><!--amr-->83 Armor</span>
          <br />
          <!--re-->
          <span class="q2">&lt;Random enchantment&gt;</span>
          <br />
          <span><!--stat5-->+184 Intellect</span>
          <br />
          <span><!--stat7-->+275 Stamina</span>
          <!--ebstats--><!--egstats--><!--e--><!--ps-->
          <br />
          Durability 120 / 120</td>
      </tr>
    </table>
    <table>
      <tr>
        <td>Requires Level<!--rlvl-->91
          <div class="whtt-sellprice">Sell Price:
            <span class="moneygold">41</span>
            <span class="moneysilver">61</span>
            <span class="moneycopper">90</span>
          </div>
        </td>
      </tr>
    </table>
  </htmlTooltip>
  <json>"appearances":{"6":[132245,""],"7":[132269,""],"8":[132254,""]},"armor":83,"bonustrees":[184],"classs":4,"displayid":132245,"flags2":8192,"id":114811,"level":640,"name":"4Hexweave Leggings","reqlevel":91,"slot":7,"slotbak":7,"source":[1],"sourcemore":[{"c":11,"icon":"inv_cloth_draenorcrafted_d_01pants","n":"Hexweave Leggings","s":197,"t":6,"ti":168839}],"specs":[64,256,63,62,257,265,258,266,267],"subclass":1</json>
  <jsonEquip>"appearances":{"6":[132245,""],"7":[132269,""],"8":[132254,""]},"armor":83,"avgbuyout":53990000,"displayid":132245,"dura":120,"int":184,"reqlevel":91,"sellprice":416190,"slotbak":7,"sta":275</jsonEquip>
  <createdBy>
    <spell id="168839" name="Hexweave Leggings" icon="inv_cloth_draenorcrafted_d_01pants" minCount="1" maxCount="1">
      <reagent id="111556" name="Hexweave Cloth" quality="2" icon="inv_tailoring_hexweavethread" count="100"/>
      <reagent id="110609" name="Raw Beast Hide" quality="1" icon="inv_misc_nativebeastskin" count="4"/>
    </spell>
  </createdBy>
  <link>http://www.wowhead.com/item=114811</link>
  </item></wowhead>


Solution:

Using simplexml_load_file we can parse XMl data.

Example:

<?php
$url='http://www.wowhead.com/item=114811&xml';
$xml = simplexml_load_file($url) or die("feed not loading");
foreach($xml->item  as $items){
    echo $items->name . "<br>";
echo $items->level . "<br>";
echo $items->quality . "<br>";
echo $items->quality['id'] . "<br>";
echo $items->class . "<br>";
echo $items->class['id'] . "<br>";
echo $items->subclass . "<br>";
echo $items->subclass['id'] . "<br>";
echo $items->icon . "<br>";
echo $items->icon['displayId'] . "<br>";
echo $items->inventorySlot . "<br>";
echo $items->inventorySlot['id'] . "<br>";
echo $items->htmlTooltip . "<br>";
echo $items->json . "<br>";
echo $items->jsonEquip . "<br>";
echo $items->createdBy->spell  . " : ";
echo $items->createdBy->spell['id']  ." : ";
echo $items->createdBy->spell['name']  ." : ";
echo $items->createdBy->spell['icon']  . " : ";
echo $items->createdBy->spell['minCount']  ." : ";
echo $items->createdBy->spell['maxCount']  . "<br>";
$created_by_count=0;
foreach($items->createdBy->spell  as $myspel){
if($myspel->count()>=1) {
    foreach($myspel as $child) {
                  $created_by_count++;
      echo $child->getName(). ' : '. $child['id']. ' : ' .$child['name'] . ' : ' . $child['quality']. ' : ' . $child['icon']. ' : ' . $child['count'] . '<br/>';
}
  }
  echo 'Count createdBy='.$created_by_count. "<br>";
echo $items->link . "<br>";
}
}
?>
Share:

Monday, May 11, 2015

Message: Undefined variable: 0 in CodeIgniter PHP

Problem:

Sometime while working with CodeIngiter / PHP you may encounter "Undefined variable: 0" error.
It surprise to that is "0" (Zero) could be a variable!

Solution:

This "Undefined variable: 0" error come when you use double dollar sign in variable. so remove one dollar ($) sign from variable and error will gone.

Example:

See the below code, specially in red color, it having $$ sign:

$data = array( 'u_login' => $row->u_login,
                        'user_type_id' => $user_type_id,
'user_id'=>$row->user_id,
'transporter_id'=>$transporter_id,
'limit_cr'=>$limit_cr,
'u_c_date'=>$row->u_c_date,
'total_trucks'=>$total_trucks,
'total_liter'=>$total_liter,
'pump_id'=> $$pump_id
                        );

jut remove one $ sign.
Share:

Friday, April 17, 2015

session destroyed after redirect in codeigniter

Problem:

Working CodeIgniter framework you can face the session problem. the problem is when you storing the values in session and redirect the page. then session destroyed automatically, it is loosing session data even you have properly loaded session library $this->load->library('session') in constructor.

see the below code:

public function myset() 
{
        $this->session->set_userdata('mydata', 'data');
        redirect('/', 'refresh');
}


function index()
{
          // loosing here data
          $mydata = $this->session->userdata('mydata');

}






Solution:

As we are seeing many new frameworks are coming today. but the Mother and base of all frameworks is Core PHP,  So we must have good knowledge about Core PHP. Here I have solved this session problem by Core PHP.

Example:

session_start();
public function myset() 
{
        $_SESSION['mydata']='data'
        redirect('/', 'refresh');
}


function index()
{      $mydata='';
        if(isset($_SESSION['mydata']) && !empty($_SESSION['mydata'])) {
                  $mydata= $_SESSION['mydata']);
        }

}

Share:

Wednesday, April 15, 2015

How to use multilanguage in CodeIgniter

Problem:

Suppose you want to use Italian language in CodeIgniter then how to do it?



Solution:

CodeIgniter provide a facility that you can store the predefined words in array in separate files. after that you can use it as per your requirements.

Example:

1- create a folder name "italian" under "application\language".
2- under this folder create a "italian_lang.php" file as below matter. change it's matter as per your requirements.
<?php
$lang['home_slide_1']        = "Rendi <span>unici</span> i tuoi parastinchi";
$lang['home_latuaidea_title']        = "La tua <br/>idea";
/// and many more....
?>
now your file is created, now the question is that how to use it?
4- in view where you want to write italian text at the top of file load this file as below method:
$this->lang->load('italian', 'italian');


<?php echo $this->lang->line('home_slide_1');?>
<?php echo $this->lang->line('home_latuaidea_title');?>


Share:

Sunday, March 29, 2015

File upload in CodeIgniter

Problem:

How to upload file in CodeIgniter?
You can simply use $_FILES array to upload image. But if you want to use CodeIgniter library to upload file, then how can you achieve this? 

Solution:

You can use $this->load->helper('form'); to generate form.
After that configure using $config[], set this $config[] same as $this->load->library('upload', $config);
and upload like this
$this->upload->do_upload('transporter_image');

Error may occur during file upload so you can get error list by using

$his->upload->display_errors());
If file uploaded the get the information by this method:
$this->upload->data();

Example:

VIEW FILE
transporter_form.php
<html>
<head>
<title>File uploading in CodeIgniter</title>
</head>
<body>
<?php echo form_open_multipart('Transporter/transporterlist/');?>
<input type="file" name="transporter_image" size="20" />
<br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
============================================
CONTROLLER FILE
Transporter.php
<?php
class Transporter extends CI_Controller {
        public function __construct()
        {
                parent::__construct();
                $this->load->helper('form');
        }

        public function index()
        {
                $this->load->view('transporter_form', array('error' => ' ' ));
        }

        public function transporterlist ()
        {
        $config['upload_path']          = './images/transporter/';
            $config['allowed_types']        = 'gif|jpg|png';
            $config['max_size']             = 100;

            $config['max_width']            = 1024;
            $config['max_height']           = 768;
        $config['file_name']           = 'file_name.jpg';// set file name here
        $this->load->library('upload', $config);
        if(!$this->upload->do_upload('transporter_image')) {
                    $data['imgerror']= array('error' => $this->upload->display_errors());
        } else {
                    $data['imgsuccess'] = 'Image uploaded';//array('success' => $this->upload->data());
        }
        $this->load->view('successpage',$data);
        }
}
?>
==============================================
VIEW FILE
successpage.php
<html>
<head>
<title></title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<?php
    if(isset($imgsuccess)){
        echo $imgsuccess;
    }
?>

<ul>
<?php
if(isset($imgerror)) {
    foreach ($imgerror as $item => $value):?>
        <li><?php echo $item;?>: <?php echo $value;?></li>
<?php
    endforeach;
}
?>
</ul>
</body>
</html>








Share:

Prevent XSS in CodeIgniter

Problem:

How to prevent XSS Cross Site Scripting in CodeIgniter

Solution:

use $this->security->xss_clean($input_data); method
OR
set $config['global_xss_filtering']=TRUE;

Example:

$input_data = $this->security->xss_clean($input_data);
or add this line in config.php file
$config['global_xss_filtering'] = TRUE;
Share:

Binding Where IN Clause in CodeIgniter

Problem:

How to bind multiple and single value in where IN sql clause using CodeIgniter

Solution:

Pass array variable in query

Example:

Passing single numeric value using array.

$sql = "SELECT * FROM tbl_name WHERE id IN ? AND nm = ? AND code = ?";
$this->db->query($sql, array(array(1), 'nm123', 'c123'));

Passing multiple numeric value using array.
$sql = "SELECT * FROM tbl_name WHERE id IN ? AND nm = ? AND code = ?";
$this->db->query($sql, array(array(1, 2, 3), 'nm123', 'c123'));

Passing single string value using array.
$sql = "SELECT * FROM tbl_name WHERE id IN ? AND nm = ? AND code = ?";
$this->db->query($sql, array(array('a1'), 'nm123', 'c123'));

Passing multiple string value using array.
$sql = "SELECT * FROM tbl_name WHERE id IN ? AND nm = ? AND code = ?";
$this->db->query($sql, array(array('a1', 'a2', 'a3'), 'nm123', 'c123'));

Share:

Saturday, March 28, 2015

load model in view codeigniter

Problem:

How to load model in CodeIgniter view? It is not a good idea to load model in view, but sometime it is a requirement to load model in view.

Solution:

Create the instance of CodeIgniter as below:
$ci_inst =&get_instance();

Then load your model as below:
$ci_inst->load->model('model_name');

now you can access model as below:
$rs_truck=$ci_inst->model_name->function_method_name(parameter);

Example:

$ci_inst =&get_instance();
$ci_inst->load->model('truck_model');
$rs_truck=$ci->truck_model->get_trucks_by_transporter_id(1);
Share:

Wednesday, March 25, 2015

Email Blaster

Email Blaster
*Features
- Send unlimited emails.
- Send test email, so you can see your email format and looks.
- Show real time progress in counting sent emails.
- Show progress in percentage(%)
- Send email both format Text and HTML format.
- Alternate Solution of Cron Job(Less feature).
- Alternate Solution of SQL Agent Job(Less feature).
- Solution of Script Timeout.






















































Share:

Monday, March 23, 2015

Custom library in CodeIgniter

Custom library in CodeIgniter:

CodeIgniter is a MVC PHP Framework. Do you know this framework is very fast PHP framework. It is designed to create a dynamic, flexible & SEO friendly web application.
Now days CodeIgniter is very famous MVC framework. In past time when you work in Core PHP with OOP; you have developed own custom library which have many utilities functions which you uses in different Projects. This custom library save your time and remove complexity.

Now you are moving to modern programming languages like CodeIgniter  framework. Now the question is how to use that custom library in this CodeIgniter framework?


See below class with having functions which is your custom library:
<?php
// Class name is "Myclass". but you can change it with any name
class Myclass {
   // Declare local variable
   var $temp;
   // This is constructor of "Myclass" here you can initialize local variables etc.
    public function __construct(){
       // set local variable value with single space.
       $this->temp='';
    }
 
   // this is method will call after delete record in CodeIgniter Controller
    public function message_del() {
        // Add here your usefull code
        $this->temp='    Record Deleted.';
        return $this->temp;
    }
 
// this is method will call after edit record in CodeIgniter Controller
    public function message_edit() {
        // Add here your usefull code
           $this->temp='    Record Edited.';
        return $this->temp;
    }

   // this is method will call after add record in CodeIgniter Controller
    public function message_add() {
            // Add here your usefull code
        $this->temp='    Record Added.';
        return $this->temp;
    }
}
?>


Now how to use above class in CodeIgniter?  Follow below steps o how to use.
//Create Myclass.php file in codeigniter "application\libraries\"

//Myclass.php
<?php
// this is default CodeIgniter code Do not delete it
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Myclass {
   // Declare local variable , note that $temp variable will return from it's class's methods
   var $temp;
   var $CI;
   public function __construct(){
      // set CodeIgniter instance object here. but it is not necessary.
       $this->CI =&get_instance();
       // set local variable value with single space.
       $this->temp='';
    }
     // this is method will call after delete record in CodeIgniter Controller
    public function message_del() {
        // Add here your code which delete record from mysql database.
        $this->temp='    Record Deleted.';
        return $this->temp;
    }
 
// this is method will call after edit record in CodeIgniter Controller
    public function message_edit() {
         // Add here your code which edit record in mysql database.
           $this->temp='    Record Edited.';
        return $this->temp;
    }

   // this is method will call after add record in CodeIgniter Controller
    public function message_add() {
            // Add here your code which add record in mysql database.
        $this->temp='    Record Added.';
        return $this->temp;
    }
}
?>

Now how to use above class in any controller class
Create Category.php controller file in "application\controllers\" folder
Category.php


<?php

// this is default CodeIgniter code Do not delete it
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// This is the Controller class it must always extends with  CI_Controller
class Category extends CI_Controller {

// This the default constructor with same name as Category class
    function Category() {
        //it is necessary to call parent class's (CI_Controller) constructor
        parent::__construct();

        // this is the your Myclass class in Myclass.php file in "application\libraries\" folder
        // this is the way to load your custom class. Make sure it should be small case letter
        $this->load->library('myclass');
    }
    public function index() {
        // use own logic here, you can make empty it.
    }
    // suppose you want to use MyClass.php >message_add method here
    public function addrecord() {
        // this is the way to calling method message_add()
         $data['ans']=$this->myclass->message_add();
//now load "result_view" with ans data
        $this->load->view('result_view',$data);
    }
    // suppose you want to use MyClass.php method message_edit() here
    public function editrecord() {
        // this is the way to calling method message_edit()
        $data['ans']=$this->myclass-message_edit();
//now load "result_view" with ans data
       $this->load->view('result_view',$data);

    }
    // suppose you want to use MyClass.php method message_del() here
    public function deleterecord() {
        // this is the way to calling method message_del()
         $data['ans']=$this->myclass-message_del();
        //now load "result_view" with ans data
        $this->load->view('result_view',$data);
    }   
}
?>



Now how to use above class in any controller class
Create 
result_view.php  view file in "application\views\" folder
result_view.php

<?php
//now access the variable  "$ans"  which  set in  $data['ans']=$this->myclass-message_del();  
// and load it in the view as $this->load->view('result_view',$data);

if(isset($ans)) {
          echo $ans;

       }
?>


Share:

Sunday, March 22, 2015

Fatal error: Call to a member function num_rows() on a non-object in

Problem:

While working with CodeIgniter you can get this "Fatal error: Call to a member function num_rows() on a non-object in...." error. You can also surprise that every thing is okay and every thing is okay in your sql.

Solution:

Some time you used different my sql Database name in local and production server, and you have mentioned wrong database name in your config.php file, So just verify the Database name and this error will gone.




Share:

Saturday, November 08, 2014

Configure codeigniter in wamp 2.5

PROBLEM:
If you are a PHP Developer the WAMP is a good environment. You can do the things easily with WAMP.. You can download WAMP from it's website. Recently WAMP have made many changes, in past WAMP version you simply web ste in the "www" folder and eailsy open the site. For example:
While working on codeigniter with wamp server you just past the codeigniter project directory to the wamp server "D:\wamp\www" folder. but if you have the wamp server 2.5 then your project will not work. means wrong path will shown in the browser .
 
But recent version of WAMp have made many changes so your site will not open. So what waht made to open website with recent WAMP? in the other words How to configure PHP website or codeigniter in wamp 2.5 ?

SOLUTION:
open "index.php" file which under "www" folder
and find the statement "$suppress_localhost=true"
and change it as below:

"$suppress_localhost=false"
Share:

Friday, November 07, 2014

Show sql query in Codeigniter

Problem:

While working in Codeigniter framework and execution some sql query. but the sql query result is not coming as you want. In this case there are something wrong with your sql queries. Then what you will do? the answer is that you will see the what exact sql query you are executing in Codeigniter.
So how can you show or see sql query in Codeigniter?

Solution:
you can use this statement after execution sql query

you can use $this->db->last_query();  statement as below:

Example:

$sql = "SELECT district_id FROM district_names where districtname= ?";
$rsMatter=$this->db->query($sql, array($districtname));
echo $this->db->last_query();
Share:

Pass sql result in codeigniter view

Problem:

PHP Codeigniter framework is a good MVC framework for PHP developer. While passwing result to it's view you may face the sql result problem. The problem is that you can not see sql result in the "View". You can face the belwo error:
-----------------------------------------------------
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: statename_list
( ! ) Fatal error: Call to a member function result() on a non-object in.
-----------------------------------------------------
So what is the proper method to pass sql result to Codeigniter view?

Solution:

You always pass array variable in the view to overcome this problem. Here I am showing the proper way that how you pass sql result to view 

Example:

IN CONTROLLER :
<?php
passed $statename_list data records from mysql table by controller:
$statename_list=$this->main_model->get_statenames();
$this->load->view('main_include/6_main_content_view',$statename_list);
?>

IN VIEW :
<?php
$this->load->database();
 foreach ($statename_list->result() as $row_state) {
 echo $row_state->statename;
 //$matter_id=$row_state->matter_id;
 }
?>

By using above statements you will get the listed below error:
---------------------------------------------------------------------------------
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: statename_list
( ! ) Fatal error: Call to a member function result() on a non-object in.
---------------------------------------------------------------------------------

PROPER SOLUTION: In controller use as:

$statename_list=$this->main_model->get_statenames();
$data['statename_list']=$statename_list;

and pass it in view as:
$this->load->view('main_include/6_main_content_view',$data);

and use it as in view:
    <?php foreach ($statename_list->result() as $row_state) {
 $statename= $row_state->statename;
 $state_id=$row_state->state_id;
 ?>
Share:

Remove index.php in Codeigniter

Remove index.php from url in Codeigniter

Just copy these listed below 4 line of code ".htaccess" file in the root directory of codeigniter framework. if you have not then create it. After this restart your Server and check it.


RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
Share:

Saturday, July 05, 2014

CodeIgniter Undefined property CI_Loader $session codeigniter error

Problem:

If you works in CodeIgniter and play with session then you can get this error message :
Undefined property: CI_Loader::$session

CodeIgniter Undefined property CI_Loader $session codeigniter error

A PHP Error was encountered CodeIgniter
CodeIgniter error

 Severity: Notice
Message: Undefined property: CI_Loader::$session

Solution:

It means that you have not loaded session library in it controller's index or constructor as
$this->load->library('session'); 

Example:

To prevent this error message use listed below code:

public function index() {
        $this->load->library('session');
}
Share:

Saturday, October 05, 2013

Remove Controller and it's method form codeigniter

How to remove Controller in  codeigniter and it's method just show it's parameter in url for ex:


http://localhost:90/CodeIgniter_2.1.4_new/category/show/this-is-the-test.html
as
http://localhost:90/CodeIgniter_2.1.4_new/this-is-the-test.html

Goto routes.php under config directory:
write this listed below line
$route['(:any)'] = "category/show/$1";
==============================
====================================================
create a new file "category.php"
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Category extends CI_Controller {
    public function index() {
        $this->load->view('welcome_message');
    }
    public function show($text) {
            echo "aaaaa".$text;  
    }
}
Share:

Send email in Codeigniter

Send email in Codeigniter


$this->load->library('email');
$this->email->from('my@my-site.com', 'My Name');
$this->email->subject('Test subject');
$this->email->message('Testing email.');
$this->email->attach('/path/img1.jpg');
$this->email->send();

Share:

Use value in index method in Codeigniter

Use value in index method in Codeigniter

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Category extends CI_Controller {
    public function index($param)
    {
        echo $param;
        $this->load->view('category_
message');
    }
    public function _remap($param) {
        $this->index($param);
    }
}

use is as:
http://localhost:90/CodeIgniter_2.1.4/category/laptop
Share:

Ads Inside Post

Powered by Blogger.

Archive