Codeigniter

Write a code in CI common library file :

view : 

<?php
for($i=0;$i<count($schedule_list);$i++){
?>
<div id=”srch_results_box”>
<div class=”srch_rslt_tourname”>
<img src=”images/scc_rslt_img.png” width=”132″ height=”62″><br>
<span class=”srch_rslt_tourname1″>
<?php
$tournament = $this->common->GetTournament($schedule_list[$i][‘tournament’]);
echo $tournament;
?>
</span>
</div><!– srch_rslt_tourname –>
<div class=”srch_rslt_match”>
<span class=”srch_rslt_match1″><?php echo $schedule_list[$i][‘fixture_name’];?></span>
</div><!– srch_rslt_match –>
<div class=”srch_rslt_teamname”>

<img src=”images/srch_rslt_tname_img.png” width=”92″ height=”92″><br>
<span class=”srch_rslt_teamname1″>
<?php
$team_name = $this->common->GetTeam($schedule_list[$i][‘team_a’]);
echo $team_name;
?>
</span>
</div><!– srch_rslt_teamname –>
<div class=”srch_rslt_vs”>
<span class=”srch_rslt_vs1″>Vs</span>
</div><!– srch_rslt_match –>
<div class=”srch_rslt_teamname”>
<img src=”images/srch_rslt_tname_img.png” width=”92″ height=”92″><br>
<span class=”srch_rslt_teamname1″>
<?php
$team_name = $this->common->GetTeam($schedule_list[$i][‘team_b’]);
echo $team_name;
?>
</span>
</div><!– srch_rslt_teamname –>
<div class=”srch_rslt_venuedate”>
<span class=”srch_rslt_venuedate1″>
<?php
$team_venue = $this->common->GetVenue($schedule_list[$i][‘venue’]);
echo $team_venue;
?>
</span>
<span class=”srch_rslt_venuedate2″>
Between <?php echo $schedule_list[$i][‘start_time’];?> – <?php echo $schedule_list[$i][‘end_time’];?>
</span>
<span class=”srch_rslt_venuedate3″>
<?php echo date(‘l jS F, Y’,strtotime($schedule_list[$i][‘fixture_date’])).”.”;?>
</span>
</div><!– srch_rslt_venue –>
</div><!– srch_rslt_BOX –>
<?php }?>

————————————-

CI -> common :

public function GetTeam($id)
{
$this->CI->db->where(‘team_id’,$id);
$this->CI->db->where(‘status’,’Y’);
$query = $this->CI->db->get(‘scc_team’);

foreach($query->result() as $result)
{
$team_name = $result->team_name;
}
return $team_name;
}

public function GetVenue($id)
{
$this->CI->db->where(‘id’,$id);
$this->CI->db->where(‘status’,’1′);
$query = $this->CI->db->get(‘scc_venue’);

foreach($query->result() as $result)
{
$team_venue = $result->name;
}
return $team_venue;
}

——————————————————————————————————————————————————————————–

Get max value from table :

function GetMaxValue($tablename,$colname)
{

$this->db->select_max(‘banner_order’);
$query = $this->db->get(TBL_BANNER);
$result = $query->result();
return $result;
}

————————————————————————–

To get all session in view pages :

$this->session->all_userdata();

———————————————————————-

URL Validation :

public function url_validation($value)
{
if(!$value)
{
$this->form_validation->set_message(‘url_validation’, ‘External Link field is required’);
return FALSE;
}else if($value)
{
if(!preg_match(‘|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i’, $value))
{
$this->form_validation->set_message(‘url_validation’, ‘Please enter a valid URL’); return FALSE;
} else {
return TRUE;
}
}
}

———————————————————————————————————————————

Upload Image path in Config file :

$bsurl = ‘http’ . ((isset($_SERVER[‘HTTPS’]) && $_SERVER[‘HTTPS’] == ‘on’) ? ‘s’ : ”).’://’.$_SERVER[‘HTTP_HOST’].str_replace(‘//’,’/’,dirname($_SERVER[‘SCRIPT_NAME’]).’/’);

$bsfurl = $_SERVER[‘DOCUMENT_ROOT’].dirname($_SERVER[‘SCRIPT_NAME’]).’/’;

$config[‘base_url’] = $bsurl;
$config[‘base_folder_url’] = $bsfurl;

$config[‘album_folder_path’] = $bsfurl.”upload/album/”;
$config[‘album_file_path’] = $bsurl.”upload/album/”;

FCK Editor Integration :

Controller :  (Project – SharjahCC)

function __construct()
{
parent::__construct();
$fckeditorConfig = array(
‘instanceName’ => ‘a_desc’,
‘BasePath’ => base_url().’fckeditor/’,
‘ToolbarSet’ => ‘Default’,
‘Width’ => ‘650’,
‘Height’ => ‘300’,
‘Value’ => ”
);
$this->load->library(‘fckeditor’, $fckeditorConfig);

$this->load->model(‘admin/legents_model’);
$this->load->model(‘admin/modeladmin’);
$this->modeladmin->isLogged();
}

View :

<div>Long Description<font color=”#931010″> *</font> </div>

<div>
<?php set_value(‘long_description’); echo $this->fckeditor->Create(‘long_description’); ?>
<?php echo form_error(‘long_description’); ?>
</div>

——————————————————————————————————————————–

Export Excel :

Model :

public function export_excel()
{
$sql = “SELECT * FROM manage_newsletter order by id DESC”;
$recordSet = $this->db->query($sql);
//echo $sql;
//die;
if($recordSet->num_rows() > 0) {
$res[] = array(‘id’,’name’,’email’,’country’);
$i=1;
foreach($recordSet->result() as $result)
{
//$res[] = ”.$i.’,’.$this->common->date_formate($result->login_date).’,’.$this->common->time_formate($result->login_date).’,’.$result->ip_address.’,’.$result->browser.’\r\n’;
$res[] = array($i,$result->name,$result->email,$result->country);
$i++;
}
} else { $res = ‘No Records’; }

//print_r($res);

$myFile = $this->config->item(‘csv_folder_path’).”Report_File.csv”;
$fh = fopen($myFile, ‘w’) or die(“Can’t open file”);
foreach ($res as $fields) {
fputcsv($fh, $fields);
}
fclose($fh);
//return $recordSet;
}

view :

<div style=”width:150px; line-height:35px; padding-top:20px; height:40px;”>
<a href=”<?php echo $this->config->item(‘csv_file_path’);?>Report_File.csv” style=”width:150px; background:url(<?php echo base_url(); ?>images/admin/excel.png) no-repeat; padding-left:25px; padding-top:4px; padding-bottom:4px;”>

Export to Excel

</a>
</div>

Controller :

public function index()
{
$type = $this->input->get(‘type’);
$data[‘controller’]         = ‘newsletter’;
$data[‘delete_link’]         = base_url().’admin/’.$data[‘controller’].”/delete_newsletter/{{ID}}/”;
$data[‘export’]                = base_url().’admin/’.$data[‘controller’].”/export_excel”;
$data[‘newsletter’]         = $this->newsletter_model->getpage($type);
$this->newsletter_model->export_excel();
$this->load->view(‘admin/common/header’);
$this->load->view(‘admin/common/left’);
$this->load->view(‘admin/manage_newletter’,$data);
$this->load->view(‘admin/common/footer’);
}

——————————————————————————————————————————————————————————————–

Codeigniter validations :

http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html

Check 2 fileds validation wheather both are having same value  or not  :

$this->form_validation->set_rules(‘tyre_specification1’, “Price”, ‘trim|decimal|required|xss_clean|matches[tyre_specification2]’);
$this->form_validation->set_rules(‘tyre_specification2’, “Price”, ‘trim|decimal|required|xss_clean|matches[tyre_specification1]’);

Code For Already Exit – insert:

$this->form_validation->set_rules($titleField, “Country”, ‘callback_role_exists_name’);

public function role_exists_name($key)
{
if(!$key)
{
$this->form_validation->set_message(‘role_exists_name’, ‘Country name field is required’);
return FALSE;
}
else if($key)
{
$this->db->where(‘province_name’,$key);
$query = $this->db->get(‘province’);
if ($query->num_rows() > 0)
{
$this->form_validation->set_message(‘role_exists_name’, ‘Country name already exists’);
return FALSE;
}
else
{
return TRUE;
}
}
}

Code For Already Exit – update :

$this->form_validation->set_rules($titleField, “Country”, ‘callback_role_exists_name_update’);

public function role_exists_name_update($key)
{
$province_id = $this->uri->segment(4, 0);
if(!$key)
{
$this->form_validation->set_message(‘role_exists_name_update’, ‘Country name field is required’);
return FALSE;
}
else if($key)
{
$this->db->where(‘province_name’,$key);
$this->db->where(‘province_id !=’,$province_id);
$query = $this->db->get(‘province’);

if ($query->num_rows() > 0)
{
$this->form_validation->set_message(‘role_exists_name_update’, ‘Country name already exists’);
return FALSE;
}
else
{
return TRUE;
}
}
}

————————————————————————–

Inserting Data :

———————————————–

$this->db->insert();

Generates an insert string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:

$data = array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
);

$this->db->insert(‘mytable’, $data);

// Produces: INSERT INTO mytable (title, name, date) VALUES (‘My title’, ‘My name’, ‘My date’)

The first parameter will contain the table name, the second is an associative array of values.

Here is an example using an object:

/*
class Myclass {
var $title = 'My Title';
var $content = 'My Content';
var $date = 'My Date';
}
*/

$object = new Myclass;

$this->db->insert(‘mytable’, $object);

// Produces: INSERT INTO mytable (title, content, date) VALUES (‘My Title’, ‘My Content’, ‘My Date’)

The first parameter will contain the table name, the second is an object.

Note: All values are escaped automatically producing safer queries.

$this->db->insert_batch();

Generates an insert string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:

$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name' ,
'date' => 'Another date'
)
);

$this->db->insert_batch(‘mytable’, $data);

// Produces: INSERT INTO mytable (title, name, date) VALUES (‘My title’, ‘My name’, ‘My date’), (‘Another title’, ‘Another name’, ‘Another date’)

The first parameter will contain the table name, the second is an associative array of values.

Note: All values are escaped automatically producing safer queries.

$this->db->set();

This function enables you to set values for inserts or updates.

It can be used instead of passing a data array directly to the insert or update functions:

$this->db->set('name', $name);
$this->db->insert('mytable');

// Produces: INSERT INTO mytable (name) VALUES (‘{$name}’)

If you use multiple function called they will be assembled properly based on whether you are doing an insert or an update:

$this->db->set('name', $name);
$this->db->set('title', $title);
$this->db->set('status', $status);
$this->db->insert('mytable');

set() will also accept an optional third parameter ($escape), that will prevent data from being escaped if set to FALSE. To illustrate the difference, here is set() used both with and without the escape parameter.

$this->db->set('field', 'field+1', FALSE);
$this->db->insert('mytable');
// gives INSERT INTO mytable (field) VALUES (field+1)

$this->db->set(‘field’, ‘field+1’);
$this->db->insert(‘mytable’);
// gives INSERT INTO mytable (field) VALUES (‘field+1’)

You can also pass an associative array to this function:

$array = array('name' => $name, 'title' => $title, 'status' => $status);

$this->db->set($array);
$this->db->insert(‘mytable’);

Or an object:

/*
class Myclass {
var $title = 'My Title';
var $content = 'My Content';
var $date = 'My Date';
}
*/

$object = new Myclass;

$this->db->set($object);
$this->db->insert(‘mytable’);

————————————————————————————————————————————————————————————-

Updating Data :

————————————————–

$this->db->update();

Generates an update string and runs the query based on the data you supply. You can pass an array or an object to the function. Here is an example using an array:

$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);

$this->db->where(‘id’, $id);
$this->db->update(‘mytable’, $data);

// Produces:
// UPDATE mytable
// SET title = ‘{$title}’, name = ‘{$name}’, date = ‘{$date}’
// WHERE id = $id

Or you can supply an object:

/*
class Myclass {
var $title = 'My Title';
var $content = 'My Content';
var $date = 'My Date';
}
*/

$object = new Myclass;

$this->db->where(‘id’, $id);
$this->db->update(‘mytable’, $object);

// Produces:
// UPDATE mytable
// SET title = ‘{$title}’, name = ‘{$name}’, date = ‘{$date}’
// WHERE id = $id

Note: All values are escaped automatically producing safer queries.

You’ll notice the use of the $this->db->where() function, enabling you to set the WHERE clause. You can optionally pass this information directly into the update function as a string:

$this->db->update('mytable', $data, "id = 4");

Or as an array:

$this->db->update('mytable', $data, array('id' => $id));

You may also use the $this->db->set() function described above when performing updates.

$this->db->update_batch();

Generates an update string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:

$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name 2' ,
'date' => 'My date 2'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name 2' ,
'date' => 'Another date 2'
)
);

$this->db->update_batch(‘mytable’, $data, ‘title’);

// Produces:
// UPDATE `mytable` SET `name` = CASE
// WHEN `title` = ‘My title’ THEN ‘My Name 2’
// WHEN `title` = ‘Another title’ THEN ‘Another Name 2’
// ELSE `name` END,
// `date` = CASE
// WHEN `title` = ‘My title’ THEN ‘My date 2’
// WHEN `title` = ‘Another title’ THEN ‘Another date 2’
// ELSE `date` END
// WHERE `title` IN (‘My title’,’Another title’)

The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.

Note: All values are escaped automatically producing safer queries.

————————————————————————————————————————————————————————————–

The following functions allow you to build SQL SELECT statements.

Note: If you are using PHP 5 you can use method chaining for more compact syntax. This is described at the end of the page.

$this->db->get();

Runs the selection query and returns the result. Can be used by itself to retrieve all records from a table:

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

// Produces: SELECT * FROM mytable

The second and third parameters enable you to set a limit and offset clause:

$query = $this->db->get('mytable', 10, 20);

// Produces: SELECT * FROM mytable LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)

You’ll notice that the above function is assigned to a variable named $query, which can be used to show the results:

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

foreach ($query->result() as $row)
{
echo $row->title;
}

Please visit the result functions page for a full discussion regarding result generation.

$this->db->get_where();

Identical to the above function except that it permits you to add a “where” clause in the second parameter, instead of using the db->where() function:

$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);

Please read the about the where function below for more information.

Note: get_where() was formerly known as getwhere(), which has been removed

$this->db->select();

Permits you to write the SELECT portion of your query:

$this->db->select('title, content, date');

$query = $this->db->get(‘mytable’);

// Produces: SELECT title, content, date FROM mytable

Note: If you are selecting all (*) from a table you do not need to use this function. When omitted, CodeIgniter assumes you wish to SELECT *

$this->db->select() accepts an optional second parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks. This is useful if you need a compound select statement.

$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE);
$query = $this->db->get('mytable');

$this->db->select_max();

Writes a “SELECT MAX(field)” portion for your query. You can optionally include a second parameter to rename the resulting field.

$this->db->select_max('age');
$query = $this->db->get('members');
// Produces: SELECT MAX(age) as age FROM members

$this->db->select_max(‘age’, ‘member_age’);
$query = $this->db->get(‘members’);
// Produces: SELECT MAX(age) as member_age FROM members

$this->db->select_min();

Writes a “SELECT MIN(field)” portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.

$this->db->select_min('age');
$query = $this->db->get('members');
// Produces: SELECT MIN(age) as age FROM members

$this->db->select_avg();

Writes a “SELECT AVG(field)” portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.

$this->db->select_avg('age');
$query = $this->db->get('members');
// Produces: SELECT AVG(age) as age FROM members

$this->db->select_sum();

Writes a “SELECT SUM(field)” portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.

$this->db->select_sum('age');
$query = $this->db->get('members');
// Produces: SELECT SUM(age) as age FROM members

$this->db->from();

Permits you to write the FROM portion of your query:

$this->db->select('title, content, date');
$this->db->from('mytable');

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

// Produces: SELECT title, content, date FROM mytable

Note: As shown earlier, the FROM portion of your query can be specified in the $this->db->get() function, so use whichever method you prefer.

$this->db->join();

Permits you to write the JOIN portion of your query:

$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');

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

// Produces:
// SELECT * FROM blogs
// JOIN comments ON comments.id = blogs.id

Multiple function calls can be made if you need several joins in one query.

If you need a specific type of JOIN you can specify it via the third parameter of the function. Options are: left, right, outer, inner, left outer, and right outer.

$this->db->join('comments', 'comments.id = blogs.id', 'left');

// Produces: LEFT JOIN comments ON comments.id = blogs.id

$this->db->where();

This function enables you to set WHERE clauses using one of four methods:

Note: All values passed to this function are escaped automatically, producing safer queries.

  1. Simple key/value method: $this->db->where('name', $name);// Produces: WHERE name = ‘Joe’Notice that the equal sign is added for you.If you use multiple function calls they will be chained together with AND between them:$this->db->where('name', $name);
    $this->db->where('title', $title);
    $this->db->where('status', $status);
    // WHERE name = ‘Joe’ AND title = ‘boss’ AND status = ‘active’
  2. Custom key/value method:You can include an operator in the first parameter in order to control the comparison:$this->db->where('name !=', $name);
    $this->db->where('id <', $id);
    // Produces: WHERE name != ‘Joe’ AND id < 45
  3. Associative array method: $array = array('name' => $name, 'title' => $title, 'status' => $status);$this->db->where($array);// Produces: WHERE name = ‘Joe’ AND title = ‘boss’ AND status = ‘active’You can include your own operators using this method as well: $array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);$this->db->where($array);
  4. Custom string:You can write your own clauses manually: $where = "name='Joe' AND status='boss' OR status='active'";$this->db->where($where);

$this->db->where() accepts an optional third parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks.

$this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);

$this->db->or_where();

This function is identical to the one above, except that multiple instances are joined by OR:

$this->db->where('name !=', $name);
$this->db->or_where('id >', $id);

// Produces: WHERE name != ‘Joe’ OR id > 50

Note: or_where() was formerly known as orwhere(), which has been removed.

$this->db->where_in();

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate

$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')

$this->db->or_where_in();

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate

$names = array('Frank', 'Todd', 'James');
$this->db->or_where_in('username', $names);
// Produces: OR username IN ('Frank', 'Todd', 'James')

$this->db->where_not_in();

Generates a WHERE field NOT IN (‘item’, ‘item’) SQL query joined with AND if appropriate

$names = array('Frank', 'Todd', 'James');
$this->db->where_not_in('username', $names);
// Produces: WHERE username NOT IN ('Frank', 'Todd', 'James')

$this->db->or_where_not_in();

Generates a WHERE field NOT IN (‘item’, ‘item’) SQL query joined with OR if appropriate

$names = array('Frank', 'Todd', 'James');
$this->db->or_where_not_in('username', $names);
// Produces: OR username NOT IN ('Frank', 'Todd', 'James')

$this->db->like();

This function enables you to generate LIKE clauses, useful for doing searches.

Note: All values passed to this function are escaped automatically.

      1. Simple key/value method: $this->db->like('title', 'match');// Produces: WHERE title LIKE ‘%match%’If you use multiple function calls they will be chained together with AND between them:$this->db->like('title', 'match');
        $this->db->like('body', 'match');
        // WHERE title LIKE ‘%match%’ AND body LIKE ‘%match% If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are ‘before’, ‘after’ and ‘both’ (which is the default). $this->db->like('title', 'match', 'before');
        // Produces: WHERE title LIKE '%match'
        $this->db->like(‘title’, ‘match’, ‘after’);
        // Produces: WHERE title LIKE ‘match%’$this->db->like(‘title’, ‘match’, ‘both’);
        // Produces: WHERE title LIKE ‘%match%’

If you do not want to use the wildcard (%) you can pass to the optional third argument the option ‘none’.

$this->db->like('title', 'match', 'none');
// Produces: WHERE title LIKE 'match'

  1. Associative array method: $array = array('title' => $match, 'page1' => $match, 'page2' => $match);$this->db->like($array);// WHERE title LIKE ‘%match%’ AND page1 LIKE ‘%match%’ AND page2 LIKE ‘%match%’

$this->db->or_like();

This function is identical to the one above, except that multiple instances are joined by OR:

$this->db->like('title', 'match');
$this->db->or_like('body', $match);

// WHERE title LIKE ‘%match%’ OR body LIKE ‘%match%’

Note: or_like() was formerly known as orlike(), which has been removed.

$this->db->not_like();

This function is identical to like(), except that it generates NOT LIKE statements:

$this->db->not_like('title', 'match');

// WHERE title NOT LIKE ‘%match%

$this->db->or_not_like();

This function is identical to not_like(), except that multiple instances are joined by OR:

$this->db->like('title', 'match');
$this->db->or_not_like('body', 'match');

// WHERE title LIKE ‘%match% OR body NOT LIKE ‘%match%’

$this->db->group_by();

Permits you to write the GROUP BY portion of your query:

$this->db->group_by("title");

// Produces: GROUP BY title

You can also pass an array of multiple values as well:

$this->db->group_by(array("title", "date"));

// Produces: GROUP BY title, date

Note: group_by() was formerly known as groupby(), which has been removed.

$this->db->distinct();

Adds the “DISTINCT” keyword to a query

$this->db->distinct();
$this->db->get('table');

// Produces: SELECT DISTINCT * FROM table

$this->db->having();

Permits you to write the HAVING portion of your query. There are 2 possible syntaxes, 1 argument or 2:

$this->db->having('user_id = 45');
// Produces: HAVING user_id = 45

$this->db->having(‘user_id’, 45);
// Produces: HAVING user_id = 45

You can also pass an array of multiple values as well:

$this->db->having(array('title =' => 'My Title', 'id <' => $id));

// Produces: HAVING title = ‘My Title’, id < 45

If you are using a database that CodeIgniter escapes queries for, you can prevent escaping content by passing an optional third argument, and setting it to FALSE.

$this->db->having('user_id', 45);
// Produces: HAVING `user_id` = 45 in some databases such as MySQL
$this->db->having('user_id', 45, FALSE);
// Produces: HAVING user_id = 45

$this->db->or_having();

Identical to having(), only separates multiple clauses with “OR”.

$this->db->order_by();

Lets you set an ORDER BY clause. The first parameter contains the name of the column you would like to order by. The second parameter lets you set the direction of the result. Options are asc or desc, or random.

$this->db->order_by("title", "desc");

// Produces: ORDER BY title DESC

You can also pass your own string in the first parameter:

$this->db->order_by('title desc, name asc');

// Produces: ORDER BY title DESC, name ASC

Or multiple function calls can be made if you need multiple fields.

$this->db->order_by("title", "desc");
$this->db->order_by("name", "asc");

// Produces: ORDER BY title DESC, name ASC

Note: order_by() was formerly known as orderby(), which has been removed.

Note: random ordering is not currently supported in Oracle or MSSQL drivers. These will default to ‘ASC’.

$this->db->limit();

Lets you limit the number of rows you would like returned by the query:

$this->db->limit(10);

// Produces: LIMIT 10

The second parameter lets you set a result offset.

$this->db->limit(10, 20);

// Produces: LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)

$this->db->count_all_results();

Permits you to determine the number of rows in a particular Active Record query. Queries will accept Active Record restrictors such as where(), or_where(), like(), or_like(), etc. Example:

echo $this->db->count_all_results('my_table');
// Produces an integer, like 25

$this->db->like(‘title’, ‘match’);
$this->db->from(‘my_table‘);
echo $this->db->count_all_results();
// Produces an integer, like 17

$this->db->count_all();

Permits you to determine the number of rows in a particular table. Submit the table name in the first parameter. Example:

echo $this->db->count_all('my_table');

// Produces an integer, like 25

————————————————————————————————————————————————————————————

Deleting Data :

———————————————-

$this->db->delete();

Generates a delete SQL string and runs the query.

$this->db->delete('mytable', array('id' => $id));

// Produces:
// DELETE FROM mytable
// WHERE id = $id

The first parameter is the table name, the second is the where clause. You can also use the where() or or_where() functions instead of passing the data to the second parameter of the function:

$this->db->where('id', $id);
$this->db->delete('mytable');

// Produces:
// DELETE FROM mytable
// WHERE id = $id

An array of table names can be passed into delete() if you would like to delete data from more than 1 table.

$tables = array('table1', 'table2', 'table3');
$this->db->where('id', '5');
$this->db->delete($tables);

If you want to delete all data from a table, you can use the truncate() function, or empty_table().

$this->db->empty_table();

Generates a delete SQL string and runs the query. $this->db->empty_table('mytable');

// Produces
// DELETE FROM mytable

$this->db->truncate();

Generates a truncate SQL string and runs the query.

$this->db->from('mytable');
$this->db->truncate();
// or
$this->db->truncate('mytable');

// Produce:
// TRUNCATE mytable

Note: If the TRUNCATE command isn’t available, truncate() will execute as “DELETE FROM table”.

 Method Chaining :

————————————————————-

Method chaining allows you to simplify your syntax by connecting multiple functions. Consider this example:

$this->db->select('title')->from('mytable')->where('id', $id)->limit(10, 20);

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

Note: Method chaining only works with PHP 5.

—————————————————————————————————————————————————————–

Fetch multiple records using for each :

public function GetServicesListing()
{
$sql = “SELECT * FROM products_services WHERE status = ‘Y’ AND lang_id = “.$GLOBALS[‘LANGUAGE_ID’].” AND title=’Services’ ORDER BY prod_service_id DESC”;

$recordSet = $this->db->query($sql);
if($recordSet)
{
$rs = array();
if($recordSet->num_rows() > 0)
{
foreach($recordSet->result_array() as $key =>$val)
{
$rs[]=$val;
}
}
}
else
{
return false;
}
return $rs;
}

Fetch single record using (row_array()):

public function GetProductsDetail($product_id)
{
$sql = “select * from products_services where prod_service_id='”.$product_id.”‘ AND status=’Y’ AND lang_id = ‘”.$GLOBALS[‘LANGUAGE_ID’].”‘”;

$recordSet = $this->db->query($sql);
$product_detail = $recordSet->row_array();

return $product_detail;
}

CK Editor Integration :

<script type=”text/javascript” src=”<?php echo base_url();?>editor/ckeditor/ckeditor.js”></script>

<textarea class=”ckeditor” name=”editor<?=$langId[$j-1]?>” id=”editor<?=$langId[$j-1]?>” onkeypress=”empty(‘err_long_des1’)”><?php echo set_value(‘editor’.$langId[$j-1]);?></textarea>
<script type=”text/javascript”>
CKEDITOR.replace( ‘editor<?=$langId[$j-1]?>’,{
filebrowserBrowseUrl :'<?php echo base_url(); ?>editor/ckfinder/ckfinder.html’,
filebrowserImageBrowseUrl : ‘<?php echo base_url(); ?>editor/ckfinder/ckfinder.html?Type=Images’,
filebrowserFlashBrowseUrl :'<?php echo base_url(); ?>editor/ckfinder/ckfinder.html?Type=Flash’,
filebrowserUploadUrl :'<?php echo base_url(); ?>editor/ckeditor/filemanager/connectors/php/upload.php?Type=File’,
filebrowserImageUploadUrl : ‘<?php echo base_url(); ?>editor/ckeditor/filemanager/connectors/php/upload.php?Type=Image’,
filebrowserFlashUploadUrl : ‘<?php echo base_url(); ?>editor/ckeditor/filemanager/connectors/php/upload.php?Type=Flash’});
</script>

Rule Reference

The following is a list of all the native rules that are available to use:

Rule Parameter Description Example
required No Returns FALSE if the form element is empty.
matches Yes Returns FALSE if the form element does not match the one in the parameter. matches[form_item]
is_unique Yes Returns FALSE if the form element is not unique to the table and field name in the parameter. is_unique[table.field]
min_length Yes Returns FALSE if the form element is shorter then the parameter value. min_length[6]
max_length Yes Returns FALSE if the form element is longer then the parameter value. max_length[12]
exact_length Yes Returns FALSE if the form element is not exactly the parameter value. exact_length[8]
greater_than Yes Returns FALSE if the form element is less than the parameter value or not numeric. greater_than[8]
less_than Yes Returns FALSE if the form element is greater than the parameter value or not numeric. less_than[8]
alpha No Returns FALSE if the form element contains anything other than alphabetical characters.
alpha_numeric No Returns FALSE if the form element contains anything other than alpha-numeric characters.
alpha_dash No Returns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes.
numeric No Returns FALSE if the form element contains anything other than numeric characters.
integer No Returns FALSE if the form element contains anything other than an integer.
decimal Yes Returns FALSE if the form element is not exactly the parameter value.
is_natural No Returns FALSE if the form element contains anything other than a natural number: 0, 1, 2, 3, etc.
is_natural_no_zero No Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc.
valid_email No Returns FALSE if the form element does not contain a valid email address.
valid_emails No Returns FALSE if any value provided in a comma separated list is not a valid email.
valid_ip No Returns FALSE if the supplied IP is not valid. Accepts an optional parameter of “IPv4” or “IPv6” to specify an IP format.
valid_base64 No Returns FALSE if the supplied string contains anything other than valid Base64 characters.

Note: These rules can also be called as discrete functions. For example:

Prepping Reference

The following is a list of all the prepping functions that are available to use:

Name Parameter Description
xss_clean No Runs the data through the XSS filtering function, described in the Input Class page.
prep_for_form No Converts special characters so that HTML data can be shown in a form field without breaking it.
prep_url No Adds “http://&#8221; to URLs if missing.
strip_image_tags No Strips the HTML from image tags leaving the raw URL.
encode_php_tags No Converts PHP tags to entities.

Note: You can also use any native PHP functions that permit one parameter, like trim, htmlspecialchars, urldecode, etc.

Function Reference

—————————————————-

The following functions are intended for use in your controller functions.

$this->form_validation->set_rules();

Permits you to set validation rules, as described in the tutorial sections above:

$this->form_validation->run();

Runs the validation routines. Returns boolean TRUE on success and FALSE on failure. You can optionally pass the name of the validation group via the function, as described in: Saving Groups of Validation Rules to a Config File.

$this->form_validation->set_message();

Permits you to set custom error messages. See Setting Error Messages above.

————————————————————————————————-

Image Upload height and width restriction :

if($_FILES[‘upload_a’.$l_id_arr[$i]][‘name’]!=”)
{
//$return_str = true;
$tmpName = $_FILES[‘upload_a’.$l_id_arr[$i]][‘tmp_name’];
list($width, $height, $type, $attr) = getimagesize($tmpName);
$bytes = filesize($tmpName);
$mb_bytes = (($bytes/1024)/1024);
if($mb_bytes > 1 || $width!=200 || $height!=200)
{
return false;
}
else {
$file_name_1[$i] = str_replace(“”,”_”,$_FILES[‘upload_a’.$l_id_arr[$i]][‘name’]);
$img_extn = explode(‘.’,$file_name_1[$i]);
$file_name_1[$i] = $img_extn[0].”_”.rand().”.”.$img_extn[1];
move_uploaded_file($_FILES[‘upload_a’.$l_id_arr[$i]][‘tmp_name’],$this->config->item(‘file_upload_absolute_path’).”when_change_tyre/”.$file_name_1[$i]);
//die;
}
}

——————————————————————————————————————————–

Get single field in model file :

public function tyre_structure_value($id)
{
$query=$this->db->query(“SELECT status FROM tyre_structure WHERE t_structure_id = “.$id.””);
$row_query = $query->row_array();
$query_status = $row_query[‘status’];
return $query_status;
}

—————————————————————————————————————————————————–

Upload Process :

Upload View file :

$banner_image[] = $edit_tyre_performance[$i][‘banner_image’];

$video_image[] = $edit_tyre_performance[$i][‘video_image’];

$video_file[] = $edit_tyre_performance[$i][‘video_file’];

<input type=”file” value=”” accept=”jpg|jpeg|png|JPG|JPEG|PNG” id=”upload_a<?=$langId[$j-1]?>” name=”upload_a<?=$langId[$j-1]?>” >

<input type=”file” accept=”jpg|jpeg|png|JPG|JPEG|PNG”  id=”upload_b<?=$langId[$j-1]?>” name=”upload_b<?=$langId[$j-1]?>” >

<input type=”file” value=”” accept=”flv|FLV” id=”upload_c<?=$langId[$j-1]?>” name=”upload_c<?=$langId[$j-1]?>” accept=”jpg|jpeg|png|JPG|JPEG|PNG”>

<input type=”hidden” name=”hidden_img_1<?=$langId[$j-1]?>” id=”hidden_img_1<?=$langId[$j-1]?>” value=”<?php echo $banner_image[$j-1];?>” />
<input type=”hidden” name=”hidden_img_2<?=$langId[$j-1]?>” id=”hidden_img_2<?=$langId[$j-1]?>” value=”<?php echo $video_image[$j-1];?>” />
<input type=”hidden” name=”hidden_img_3<?=$langId[$j-1]?>” id=”hidden_img_3<?=$langId[$j-1]?>” value=”<?php echo $video_file[$j-1];?>” />
<input type=”hidden” name=”performance_id” value=”<?php echo $this->uri->segment(4,0);?>” />

Upload controller file :

public function Update_Tyre_Performance()
{
$data[‘controller’]          = ‘info_tyre_center’;

if($_POST && $_POST[‘Update’] != NULL)
{
$l_id_arr = $this->input->post(‘lang_id’);

for($i = 0;$i< count($l_id_arr); $i++)
{
$upload_a = ‘upload_a’.$l_id_arr[$i];
$this->form_validation->set_rules($upload_a,”banner image”,’trim|xss_clean’);
}
$this->form_validation->set_error_delimiters(‘<span>’, ‘</span>’);

if($this->form_validation->run() == TRUE)
{
if($this->info_tyre_center_model->Update_Tyre_Performance($_POST))
{
$this->session->set_flashdata(‘newaddmsg’,’Tyre Performance has been updated successfully’);
redirect(base_url().”admin/info_tyre_center/tyre_performance”);
return TRUE;
}
}
else
{
$this->Edit_tyre_performance();
return FALSE;
}
}
else
{
$this->Edit_tyre_performance();
return FALSE;
}
}

Upload model file  :

public function Update_Tyre_Performance()
{
$l_id_arr = $this->input->post(‘lang_id’);
$performance_id = $_POST[‘performance_id’];

for($i=0;$i<count($l_id_arr);$i++)
{
$file_name_1[$i] = $_POST[‘hidden_img_1’.$l_id_arr[$i]];
$file_name_2[$i] = $_POST[‘hidden_img_2’.$l_id_arr[$i]];
$file_name_3[$i] = $_POST[‘hidden_img_3’.$l_id_arr[$i]];

if($_FILES[‘upload_a’.$l_id_arr[$i]][‘name’]!=”)
{
$file_name_1[$i] = str_replace(“”,”_”,$_FILES[‘upload_a’.$l_id_arr[$i]][‘name’]);
move_uploaded_file($_FILES[‘upload_a’.$l_id_arr[$i]][‘tmp_name’],$this->config->item(‘file_upload_absolute_path’).”tyre_performance/image/”.$file_name_1[$i]);
}

if($_FILES[‘upload_b’.$l_id_arr[$i]][‘name’]!=”)
{
$file_name_2[$i] = str_replace(“”,”_”,$_FILES[‘upload_b’.$l_id_arr[$i]][‘name’]);
move_uploaded_file($_FILES[‘upload_b’.$l_id_arr[$i]][‘tmp_name’],$this->config->item(‘file_upload_absolute_path’).”tyre_performance/image/”.$file_name_2[$i]);
}

if($_FILES[‘upload_c’.$l_id_arr[$i]][‘name’]!=”)
{
$file_name_3[$i] = str_replace(“”,”_”,$_FILES[‘upload_c’.$l_id_arr[$i]][‘name’]);
move_uploaded_file($_FILES[‘upload_c’.$l_id_arr[$i]][‘tmp_name’],$this->config->item(‘file_upload_absolute_path’).”tyre_performance/video/”.$file_name_3[$i]);
}

$sql = “update tyre_performance set banner_image='”.$file_name_1[$i].”‘,video_image='”.$file_name_2[$i].”‘,video_file='”.$file_name_3[$i].”‘ where performance_id='”.$performance_id.”‘ AND lang_id = ‘”.$l_id_arr[$i].”‘”;
//die;
$recordSet = $this->db->query($sql);
}

if($recordSet)
{
return true;
}else{
return false;
}
}

—————————————————————————————————————————————————

View Page :

Code for Delete and Change Status :

<?php
$cls = ”;
for($i=0; $i<count($pulling_rec);$i++)
{
$deleteLink = str_replace(“{{ID}}”,$pulling_rec[$i][‘pulling_id’],$delete_link);
$editLink     = str_replace(“{{ID}}”,$pulling_rec[$i][‘pulling_id’],$edit_link);
$activeLink = str_replace(“{{ID}}”,$pulling_rec[$i][‘pulling_id’],$active_link);

$cls = ($cls==’gradeC’?’gradeU’:’gradeC’);
?>

<tr>
<td align=”center” valign=”middle”><?php echo $i+1;?></td>
<td align=”left” valign=”middle”><?php echo $pulling_rec[$i][‘title’];?></td>
<?php if($pulling_rec[$i][‘status’]==’Y’) {  ?>
<td align=”center” valign=”middle”><a href=”<?php echo $activeLink; ?>”><img src=”<?php echo base_url(); ?>images/admin/unlock.png” width=”25″ height=”25″ border=”0″ /></a></td>
<?php } else { ?>
<td align=”center” valign=”middle”><a href=”<?php echo $activeLink; ?>”><img src=”<?php echo base_url(); ?>images/admin/lock.png” width=”25″ height=”25″ border=”0″ /></a></td>
<?php } ?>
<td align=”center” valign=”middle”>
<a href=”<?php echo $editLink;?>”><img src=”<?php echo base_url();?>images/admin/edit.png” width=”25″ height=”25″ border=”0″ /></a>
</td>
<td align=”center” valign=”middle”>
<a href=”javascript:Delete(‘<?php echo $deleteLink;?>’)”>
<img src=”<?php echo base_url();?>images/admin/delete.png” width=”25″ height=”25″ border=”0″ />
</a>
</td>
</tr>
<?php }?>

Model Page :

Code for Delete and Change Status :

public function change_pulling_status($id)
{
$sql = “UPDATE tyre_checkup_pulling SET status = if(status = ‘Y’,’N’,’Y’) WHERE pulling_id = “.$id.””;
$recordSet = $this->db->query($sql);
if(!$recordSet)
{
return false;
}
}

public function pulling_value($id)
{
$query=$this->db->query(“SELECT status FROM tyre_checkup_pulling WHERE pulling_id = “.$id.””);
$row_query = $query->row_array();
$query_status = $row_query[‘status’];

return $query_status;
}

public function delete_pulling_rec($id)
{
$sql = “delete from tyre_checkup_pulling where pulling_id='”.$id.”‘”;
$recordSet = $this->db->query($sql);
if($recordSet)
{
return true;
}
}

Controller Page :

Code for Delete and Change Status :

public function Pulling()
{
$data[‘controller’]     = ‘info_tyre_center’;
$data[‘pulling_rec’]    = $this->info_tyre_center_model->getPullingRec();
$data[‘add_link’]    = base_url().’admin/’.$data[‘controller’].’/Add_pulling’;
$data[‘delete_link’]    = base_url().’admin/’.$data[‘controller’].’/pulling_delete/{{ID}}’;
$data[‘edit_link’]        = base_url().’admin/’.$data[‘controller’].’/pulling_edit/{{ID}}’;
$data[‘active_link’]    = base_url().’admin/’.$data[‘controller’].’/pulling_active_link/{{ID}}’;

$this->load->view(‘admin/common/header’);
$this->load->view(‘admin/common/left’);
$this->load->view(‘admin/pulling_listing_view’,$data);
$this->load->view(‘admin/common/footer’);
}

public function pulling_active_link()
{
$id = $this->uri->segment(4,0);

$pulling_status = $this->info_tyre_center_model->change_pulling_status($id);
$statusvalue = $this->info_tyre_center_model->pulling_value($id);
if($statusvalue == ‘Y’)
{
$this->session->set_flashdata(‘statusmsg’,’State has been enabled successfully’);
}
else
{
$this->session->set_flashdata(‘statusmsg’,’State has been disabled successfully’);
}
redirect(base_url().”admin/info_tyre_center/pulling”);
return true;
}

public function pulling_delete()
{
$id = $this->uri->segment(4,0);

$del_pulling = $this->info_tyre_center_model->delete_pulling_rec($id);
if($del_pulling)
{
$this->session->set_flashdata(‘delmsg’,’Pulling has been deleted successfully’);
}
redirect(base_url().”admin/info_tyre_center/pulling”);
return true;
}

—————————————————-

Generating Query Results

There are several ways to generate query results:

result()

This function returns the query result as an array of objects, or an empty array on failure. Typically you’ll use this in a foreach loop, like this:

$query = $this->db->query("YOUR QUERY");

foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}

The above function is an alias of result_object().

If you run queries that might not produce a result, you are encouraged to test the result first:

$query = $this->db->query("YOUR QUERY");

if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
}

You can also pass a string to result() which represents a class to instantiate for each result object (note: this class must be loaded)

$query = $this->db->query("SELECT * FROM users;");

foreach ($query->result(‘User’) as $row)
{
echo $row->name; // call attributes
echo $row->reverse_name(); // or methods defined on the ‘User’ class
}

result_array()

This function returns the query result as a pure array, or an empty array when no result is produced. Typically you’ll use this in a foreach loop, like this:

$query = $this->db->query("YOUR QUERY");

foreach ($query->result_array() as $row)
{
echo $row[‘title’];
echo $row[‘name’];
echo $row[‘body’];
}

row()

This function returns a single result row. If your query has more than one row, it returns only the first row. The result is returned as an object. Here’s a usage example:

$query = $this->db->query("YOUR QUERY");

if ($query->num_rows() > 0)
{
$row = $query->row();

echo $row->title;
echo $row->name;
echo $row->body;
}

If you want a specific row returned you can submit the row number as a digit in the first parameter:

$row = $query->row(5);

You can also add a second String parameter, which is the name of a class to instantiate the row with:

$query = $this->db->query("SELECT * FROM users LIMIT 1;");

$query->row(0, ‘User’)
echo $row->name; // call attributes
echo $row->reverse_name(); // or methods defined on the ‘User’ class

row_array()

Identical to the above row() function, except it returns an array. Example:

$query = $this->db->query("YOUR QUERY");

if ($query->num_rows() > 0)
{
$row = $query->row_array();

echo $row[‘title’];
echo $row[‘name’];
echo $row[‘body’];
}

If you want a specific row returned you can submit the row number as a digit in the first parameter:

$row = $query->row_array(5);

In addition, you can walk forward/backwards/first/last through your results using these variations:

$row = $query->first_row()
$row = $query->last_row()
$row = $query->next_row()
$row = $query->previous_row()

By default they return an object unless you put the word “array” in the parameter:

$row = $query->first_row(‘array’)
$row = $query->last_row(‘array’)
$row = $query->next_row(‘array’)
$row = $query->previous_row(‘array’)

Result Helper Functions

$query->num_rows()

The number of rows returned by the query. Note: In this example, $query is the variable that the query result object is assigned to:

$query = $this->db->query('SELECT * FROM my_table');

echo $query->num_rows();

$query->num_fields()

The number of FIELDS (columns) returned by the query. Make sure to call the function using your query result object:

$query = $this->db->query('SELECT * FROM my_table');

echo $query->num_fields();

$query->free_result()

It frees the memory associated with the result and deletes the result resource ID. Normally PHP frees its memory automatically at the end of script execution. However, if you are running a lot of queries in a particular script you might want to free the result after each query result has been generated in order to cut down on memory consumptions. Example:

$query = $this->db->query('SELECT title FROM my_table');

foreach ($query->result() as $row)
{
echo $row->title;
}
$query->free_result(); // The $query result object will no longer be available

$query2 = $this->db->query(‘SELECT name FROM some_table’);

$row = $query2->row();
echo $row->name;
$query2->free_result(); // The $query2 result object will no longer be available

——————————————————————————————————————————–

Codeigniter Pagination :

———————————

Controller :

$this->load->library(‘pagination’);
$config[‘base_url’] = base_url().’/careers’;
$config[‘total_rows’] = $this->careers_model->gettotalrows();
$config[‘per_page’] = 5;
$config[‘uri_segment’] = 2;
$this->pagination->initialize($config);
$page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;
$data[‘careers_view’] = $this->careers_model->getCareersDetails($config[“per_page”], $page);

Model :

public function getCareersDetails($limit, $start)
{
$sql = “select * from “.TBL_JOBOFFER. ” order by offer_id desc LIMIT “.$start.”, “.$limit.””;

$recordSet = $this->db->query($sql);

if($recordSet)
{
$rs = array();
if($recordSet->num_rows() > 0)
{
foreach($recordSet->result_array() as $key => $val)
{
$rs[] = $val;
}
}
}else{
return false;
}
return $rs;
}

———————————-

public function gettotalrows()
{
$sql = “select count(*) as CarerTotalRows from “.TBL_JOBOFFER.”  where status=’Y'”;

$query = $this->db->query($sql);

$recordSet = $query->row_array();

$config[‘total_rows’] = 0;

if(count($recordSet) > 0)
{
if($recordSet[‘CarerTotalRows’] > 0)
{
$total_rows = $recordSet[‘CarerTotalRows’];
return $total_rows;
}
}else{
log_message(‘error’,$this->db->_error_message());
return false;
}
}

View :

<?php echo $this->pagination->create_links(); ?>

————————————————————–

Sharjah Cricket Council (SCC) :
Controller :

public function player_list()
{
$config[‘base_url’] = base_url().’/teams’;
$id = $this->uri->segment(3);

$data[‘scc_teams_list’] = $this->teams_model->getSccTeams();
$data[‘team_players’] = $this->teams_model->getPlayerList($id);

$this->load->view(‘front/common/header’);
$this->load->view(‘front/teams’,$data);
$this->load->view(‘front/common/footer’);
//$data[‘albums’] = $this->photos_model->albums();
}
——————-

public function getPlayerScore($player_id)
{
return $this->teams_model->getPlayerScore($player_id);
}

public function getPlayerWickets($player_id)
{
return $this->teams_model->getPlayerWickets($player_id);
}

public function getPlayerMatches($player_id)
{
return $this->teams_model->getPlayerMatches($player_id);
}

————————–
Model :
public function getPlayerMatches($player_id)

{
$sql = “select count(player_id) as matches from “.TBL_SCORES;
//echo $sql;
//die;
$recordSet = $this->db->query($sql);
if($recordSet)
{
$rs = array();
if($recordSet->num_rows() > 0)
{
foreach($recordSet->result_array() as $key => $val)
{
$rs[] = $val;
}
}
}else{
return false;
}
return $rs;
}

———————–

public function getPlayerList($id)
{
$sql = “select * from “.TBL_PLAYER.” where team_id='”.$id.”‘ and status=’Y'”;
//echo $sql;
//die;
$recordSet = $this->db->query($sql);
if($recordSet)
{
$rs = array();
if($recordSet->num_rows() > 0)
{
foreach($recordSet->result_array() as $key => $val)
{
$rs[] = $val;
}
}
}else{
return false;
}
return $rs;
}

—————————–
public function getPlayerScore($player_id)
{
$sql = “select SUM(run) as score from “.TBL_SCORES.” where player_id='”.$player_id.”‘”;
//die;
$recordSet = $this->db->query($sql);
if($recordSet)
{
$rs = array();
if($recordSet->num_rows() > 0)
{
foreach($recordSet->result_array() as $key => $val)
{
$rs[] = $val;
}
}
}else{
return false;
}
return $rs;
}
———————
public function getPlayerWickets($player_id)
{
$sql = “select SUM(wickets) as wickets from “.TBL_WICKETS.” where player_id='”.$player_id.”‘”;
//echo $sql;
//die;

$recordSet = $this->db->query($sql);
if($recordSet)
{
$rs = array();
if($recordSet->num_rows() > 0)
{
foreach($recordSet->result_array() as $key => $val)
{
$rs[] = $val;
}
}
}else{
return false;
}
return $rs;
}

—————————
View :
<?php

for($i=0;$i<count($team_players);$i++)
{
$ci =& get_instance();
$runs = $ci->getPlayerScore($team_players[$i][‘player_id’]);
$wickets = $ci->getPlayerWickets($team_players[$i][‘player_id’]);
$matches = $ci->getPlayerMatches($team_players[$i][‘player_id’]);
?>
<div>
<div><img src=”images/player_dummy_img.gif”>
<div><?php echo $team_players[$i][‘player_name’]?> <span>Captain</span></div>
</div>
<div> <span>Nationality : <?php echo $team_players[$i][‘country_id’]?></span><br>
<span>Matches <span>: <?php echo $matches[0][‘matches’]?></span></span><br>
<span>Runs <span>: <?php echo $runs[0][‘score’];?></span></span><br>
<span>Wickets <span>: <?php echo $wickets[0][‘wickets’]?></span></span><br>
</div>
</div>
<?php
}?>

——————————–

Codeigniter (retain the values):

set_value()

Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. The second (optional) parameter allows you to set a default value for the form. Example:

<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />

<h5>Password</h5>
<input type=”text” name=”password” value=”<?php echo set_value(‘password’); ?>” size=”50″ />

The above form will show “0” when loaded for the first time.

set_select()

If you use a <select> menu, this function permits you to display the menu item that was selected. The first parameter must contain the name of the select menu, the second parameter must contain the value of each item, and the third (optional) parameter lets you set an item as the default (use boolean TRUE/FALSE).

Example:

<select name="myselect">
<option value="one" <?php echo set_select('myselect', 'one', TRUE); ?> >One</option>
<option value="two" <?php echo set_select('myselect', 'two'); ?> >Two</option>
<option value="three" <?php echo set_select('myselect', 'three'); ?> >Three</option>
</select>

set_checkbox()

Permits you to display a checkbox in the state it was submitted. The first parameter must contain the name of the checkbox, the second parameter must contain its value, and the third (optional) parameter lets you set an item as the default (use boolean TRUE/FALSE). Example:

<input type="checkbox" name="mycheck" value="1" <?php echo set_checkbox('mycheck', '1'); ?> />
<input type="checkbox" name="mycheck" value="2" <?php echo set_checkbox('mycheck', '2'); ?> />

set_radio()

Permits you to display radio buttons in the state they were submitted. This function is identical to the set_checkbox() function above.

<input type="radio" name="myradio" value="1" <?php echo set_radio('myradio', '1', TRUE); ?> />
<input type="radio" name="myradio" value="2" <?php echo set_radio('myradio', '2'); ?> />

—————————————

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s