Monday, September 16, 2013

CodeIgniter's Pagination with a Search Term

On this article I’ll try to explain how to use CodeIgniter’s pagination library with a search term in a way that that our links look like:

Controller\action\search_term\page

CodeIgniter’s pagination library makes it easy for us to show long data lists generating tha links for the corresponding pages automatically, But it lacks a way to include a search term on the paginated results.

The problem is that if we inlcude a search term with the pagination, there is no specific function to include this search teram on the links for the following pages. As an extra complication we will solve this problem including a subset of data, on which we will apply both the pagination and an optional search term. And getting the links like this:

Controller\accion\id\termino de búsqueda\pagina.

We have the following scenario:

 - A list of cities.
 - A list of people who belong to a city.
 - We want to list the people belonging to a determined city, and we want to paginate the results, but also we want to be able to search in this result set and have a paginated result, using the same view.

On the firts page, we have the cities listing:

 <a href="personas/ver/1"> Personas en Ciudad 1</a>
 <a href="personas/ver/2"> Personas en Ciudad 2</a>
 <a href="personas/ver/3"> Personas en Ciudad 3</a>

In person controller must have two actions "show" and "show_search", this second function serves as an intermediate function to pass the data from the search string in the case of a paged search and the first function in case we do not have a search string in which case it works as a normal paginated search.

The first function:

<?php
function show($id_city, $offset = 0){
       //her we verify if the we have to handle a serch term
       //or its comming from “show_search” with a seacr term
       if ( $this->session->userdata('var_search')){
             $search_term=$this->session->userdata('var_search');
             $this->session->unset_userdata('var_search');
       }else{
             $search_term ='';
       }

       $this->load->model('m_person');
      
       //Load the pagination library
       $this->load->library('pagination');

       //We defini the structure of the links in case we have a search term
if ($search_term ==''){
             $config['base_url'] = base_url().'/index.php/person/show/'.$id_city.'/';
             $config['uri_segment'] = '4';
       }else{
             $config['base_url'] = base_url().'/index.php/person/show_search/'.$id_city.'/'.$search_term.'/';
             $config['uri_segment'] = '4';
       }

//this function it’s up to you must count the results for the pagination
//library
       $config['total_rows'] = $this->m_person->number_of_persons($id_city,$seach_term);
       $config['per_page'] = 25;
       $config['num_links'] =5;
       $config['next_link'] = '>';
       $config['prev_link'] = '<';
       $config['first_link'] = '<<';
       $config['last_link'] = '>>';

       $this->pagination->initialize($config);
       $data["page_links"] = $this->pagination->create_links();

       //we obtain the list of people using the offset data and the number of records by page, Again this is up to you
$articulos=$this->m_personas->show_persons_paginated($id_city,$search_term,$offset,$config['per_page']);
       $data['persons']=$persons;
       $data['id_city']=$id_city;
       $this->load->vars($data);

       //cargamos nuestra vista
       $this->load->view('template');
}
?>

On this function we verified if we had a search term, and according to this we changed a Little bit the link we want the pagination to generate.


In case we don’t have a search term, the Base_url for the pagination is normal (and the pagination library will add the page number), In case of having a search term we use the “show_search” action which will be included in the links. This function is the following:

<?php

function show search($id_city,$search_term='',$offset = 0){
       if (empty($_POST)){
                   
       }else{
             try {
                    $search_term=$this->input->post(search_term);
             } catch (Exception $e) {
                    $search_term ='';
             }
       }
       $this->session->set_userdata('var_search_term', $search_term);
       redirect('/personas/show/'.$id_city.'/'.$offset);
}
?>

What this function does is, grab the search term and save it on a session variable, and then redirect to the normal function in which this session variable will be used. And so this little function solves the problem.

On the view in which we show the results and the pagination links, We must have some search form, like the following:

  <div align="center">
       <?php echo form_open('person/show_search/'.$id_city.'/'); ?>
       <?php echo form_input("search_term");?>
       <?php echo form_close();?>
 </div>


I hope this information can help you in the future, and if you have any questions fell free to ask.

Thursday, June 6, 2013

How to connect CodeIgniter to MS SQL Server 2008

On this post I will try to explain step by step how to connect CodeIgniter to a MS SQL Server Database, I recently had to do it and had a few troubles to make it work, and no clear explanation, For these instructions I used XAMPP, but it can be applied to any other stack, just considering which PHP version they may have.

FOR WINDOWS XP

For Windows XP we have to use the 5.3.x PHP version, because the native SQL Client version and the PHP SQL driver compatible with windows XP wont work with higher versions, If you are using XAMPP, version 1.7.3 works perfectly. You can download old XAMPP versions from Here.

1st Step - Install the SQL Native Client from Microsoft:

For Windows XP the SQL Native Cliente 2008 version is sufficient for the version of the driver we will install on the next step, you can install 2012 version additionally, if you want to. The Client version for 2008 can be downloaded from  Here.

2nd Step - Install The Microsoft Driver for PHP for SQL Server :

To use the Microsoft Drivers for PHP for SQL Server, you most have the SQL Server Native Client from step One installed on the same PC that PHP is running.
We will download version 2 , that needs the Native Client for 2008 that we downloaded on step One , Download it from Microsoft Drivers 3.0 for PHP for SQL Server (Download Version 2 ).
Why Version 2 ?, because its the one that works with PHP versions 5.3.x, It has the following files included:

php_sqlsrv_53_ts_vc6.dll
php_pdo_sqlsrv_53_ts_vc6.dll

I used this ones, for you meay be differente, to know wich version to use you must look at the Phpinfo() in you server:
- Wich version of PHP you have (for example 5.3.x -> 53)
- Compiled with what version of C ( for example VC 6-> vc6)
- And if Thread Safety is enabled (enabled ->ts, not enabled -> nts)

You must install this driver on the extensions folder of PHP, in my case using XAMPP its in c:\xampp\php\ext

3rd Step - Changes on PHP.ini :

On the PHP configuration, especifically on the php.ini file, we must add the following, in order to activate the sqlsrv extensions:

extension=php_sqlsrv_53_ts_vc6.dll
extension=php_pdo_sqlsrv_53_ts_vc6.dll

then we must restart the web server.

4th Step - CodeIgniter Configuration:

Finally on the database.php file on the configuration folder of Codeigniter we must have the following configuration (pay attention to details):

$db['default']['hostname'] = '192.168.XX.XX'; //Ip or name of your SQL server 
$db['default']['username'] = 'sa';
$db['default']['password'] = 'yourpassword';
$db['default']['database'] = 'your_DB';
$db['default']['dbdriver'] = 'sqlsrv'; //yes, must use sqlsrv
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = FALSE; //put it on FALSE
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

And that's it, you can now use MS SQL Server as a database server for your    CodeIgniter proyect.


FOR WINDOWS 7 OR NEWER:

For Windows 7 we can use the latest version of XAMPP which comes with PHP 5.4.x so you can download it from  Here

1st Step - Install the SQL Native Client de Microsoft:

Now we do need the 2012 version of this client, you can download it from  Here

2nd Step - Install The Microsoft Driver for PHP for SQL Server :

To use the Microsoft Drivers for PHP for SQL Server, you most have the SQL Server Native Client from step One installed on the same Pc that PHP is running.
If we are using Windows 7 we can download the version 3 so that it works with our PHP version 5.4.x, download it from Microsoft Drivers 3.0 for PHP for SQL Server (Download Version 3).

It contains, among others, the files:

php_sqlsrv_54_ts.dll
php_pdo_sqlsrv_54_ts.dll
php_sqlsrv_54_nts.dll
php_pdo_sqlsrv_54_nts.dll

Acoording to wether your PHP is configured with Thread Safety(ts) or without (nts).

You must install this driver on the extensions folder of PHP, on XAMPP this is in c:\xampp\php\ext.

3rd Step - Changes on PHP.ini :

On the PHP configuration, especifically on the php.ini file, we must add the following, in order to activate the sqlsrv extensions:

extension=php_sqlsrv_54_ts.dll
extension=php_pdo_sqlsrv_54_ts.dll

And we restart the web server.

4th Step - CodeIgniter Configuration:

Finally on the database.php file on the configuration folder of Codeigniter we must have the following configuration (pay attention to details):

$db['default']['hostname'] = '192.168.XX.XX'; //Ip or name of your SQL server 
$db['default']['username'] = 'sa';
$db['default']['password'] = 'yourpassword';
$db['default']['database'] = 'your_DB';
$db['default']['dbdriver'] = 'sqlsrv'; //yes, must use sqlsrv
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = FALSE; //put it on FALSE
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;



And that's it, you can now use MS SQL Server as a database server for your    CodeIgniter project.

Well, that's all.  I hope this you find this helpful. 


Wednesday, May 29, 2013

Reduce the size SQL Server 2008 Log file

This is a very common problem, the log file on SQL Server may grow excessively and it may even fill a small server. On previous versions of SQL Server the problem was a little harder to manage, but since version 2008 reducing the size of this file can be achieve with this little script, 100% guaranteed:

Use my_db
GO
 
Alter Database my_db Set Recovery Simple
GO

Alter Database mi_db Set Recovery Full
GO

DBCC SHRINKFILE ('my_db_log', 1)
GO

Where "my_db" is the name of our database and "my_db_log" is the name of the log of your database, If you dont know it you can check it on the properties of the database.

I hope you can find this useful.