Friday, February 20, 2015

URL Rewriting for CodeIgniter

What is URL Rewriting?

URL rewriting provides shorter and more relevant-looking links to web pages on your site. This improves the readability and the search rankings of your URLs. For example, URL "a" can be rewritten as URL "b".
a) http://example.com/index.php?section=casting
b) http://example.com/casting
There are many articles on the web discussing the benefits of shorter and more relevant URLs. Let me add to them that you get to hide the used technology from both search engines and users. You'll also have a better time migrating to a different platform in case you need to. For example, if you build your web application on top of ASP.NET and use URL Rewriting, you can easily migrate to PHP (Recommended, of course) without changing your links and hence without losing all the search-ranking score for those links.

CodeIgniter Default URLs

By default, CodeIgniter uses a segment-based approach to represent URLs. Unfortunately, CodeIgniter includes the annoying "index.php" file name in the URL. For example:
http://example.com/index.php/products/view/shoes
Now, the CodeIgniter manual mentions that it's very simple to remove the "index.php" part from the URL using the following .htaccess file:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
Problem solved? Not really. This didn't work on my local machine nor on my online hosting account (Dreamhost). Why? I don't know. I don't care. I don't currently have the time to find out why.
Having already installed WordPress, I remembered that their .htaccess file works offline and online (at least in my case). I started playing around with it, checked some online resources, and devised two solutions. The local solution works on my local machine with the XAMPP server installed on it and the online solution works on my Dreamhost account.

The Local Solution

RewriteEngine On
RewriteBase /ci/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /ci/index.php/$1 [L]
The only change you need to make is to "ci" (on lines 2 and 5) which is the folder where you have your CodeIgniter application installed. In brief, this rewrite file tells your web server to apply the rewrite rule whenever a file or a directory is not found on the server. For example, if you invoke URL "c", the "contact" folder is not found on your server (Since CodeIgniter files are in the "system" folder), and accordingly the URL is rewritten to "d". This rewrite allows CodeIgniter to execute successfully (By using URL "d") while giving you the benefits of shorter URLs (URL "c").
c) http://localhost/ci/contact
d) http://localhost/ci/index.php/contact

The Online Solution

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]
There are no changes that you need to make for this .htaccess file. However, there's one important note to mention. The question mark after "index.php" on line 5 is needed on my online hosting account at Dreamhost. You might want to remove it if it doesn't work on yours. Again, I didn't have the time to investigate why this is the case. Please check the additional resources for more details.

Sunday, February 8, 2015

How to Create Triggers in MySQL

Our Database Plan

We’ll create a small example database for a blogging application. Two tables are required:
  • `blog`: stores a unique post ID, the title, content, and a deleted flag.
  • `audit`: stores a basic set of historical changes with a record ID, the blog post ID, the change type (NEW, EDIT or DELETE) and the date/time of that change.
The following SQL creates the `blog` and indexes the deleted column:

CREATE TABLE `blog` (
 `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
 `title` text,
 `content` text,
 `deleted` tinyint(1) unsigned NOT NULL DEFAULT '0',
 PRIMARY KEY (`id`),
 KEY `ix_deleted` (`deleted`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='Blog posts';
The following SQL creates the `audit` table. All columns are indexed and a foreign key is defined for audit.blog_id which references blog.id. Therefore, when we physically DELETE a blog entry, it’s full audit history is also removed.

CREATE TABLE `audit` (
 `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
 `blog_id` mediumint(8) unsigned NOT NULL,
 `changetype` enum('NEW','EDIT','DELETE') NOT NULL,
 `changetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`),
 KEY `ix_blog_id` (`blog_id`),
 KEY `ix_changetype` (`changetype`),
 KEY `ix_changetime` (`changetime`),
 CONSTRAINT `FK_audit_blog_id` FOREIGN KEY (`blog_id`) REFERENCES `blog` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Creating a Trigger

We now require two triggers:
  • When a record is INSERTed into the blog table, we want to add a new entry into the audit table containing the blog ID and a type of ‘NEW’ (or ‘DELETE’ if it was deleted immediately).
  • When a record is UPDATEd in the blog table, we want to add a new entry into the audit table containing the blog ID and a type of ‘EDIT’ or ‘DELETE’ if the deleted flag is set.
Note that the changetime field will automatically be set to the current time.
Each trigger requires:
  1. unique name. I prefer to use a name which describes the table and action, e.g. blog_before_insert or blog_after_update.
  2. The table which triggers the event. A single trigger can only monitor a single table.
  3. When the trigger occurs. This can either be BEFORE or AFTER an INSERT, UPDATE or DELETE. A BEFORE trigger must be used if you need to modify incoming data. An AFTER trigger must be used if you want to reference the new/changed record as a foreign key for a record in another table.
  4. The trigger body; a set of SQL commands to run. Note that you can refer to columns in the subject table using OLD.col_name (the previous value) or NEW.col_name (the new value). The value for NEW.col_name can be changed in BEFORE INSERT and UPDATE triggers.
The basic trigger syntax is:

CREATE
    TRIGGER `event_name` BEFORE/AFTER INSERT/UPDATE/DELETE
    ON `database`.`table`
    FOR EACH ROW BEGIN
  -- trigger body
  -- this code is applied to every 
  -- inserted/updated/deleted row
    END;
We require two triggers — AFTER INSERT and AFTER UPDATE on the blog table. It’s not necessary to define a DELETE trigger since a post is marked as deleted by setting it’s deleted field to true.
The first MySQL command we’ll issue is a little unusual:

DELIMITER $$
Our trigger body requires a number of SQL commands separated by a semi-colon (;). To create the full trigger code we must change delimiter to something else — such as $$.
Our AFTER INSERT trigger can now be defined. It determines whether the deleted flag is set, sets the @changetype variable accordingly, and inserts a new record into the audit table:

CREATE
 TRIGGER `blog_after_insert` AFTER INSERT 
 ON `blog` 
 FOR EACH ROW BEGIN
 
  IF NEW.deleted THEN
   SET @changetype = 'DELETE';
  ELSE
   SET @changetype = 'NEW';
  END IF;
    
  INSERT INTO audit (blog_id, changetype) VALUES (NEW.id, @changetype);
  
    END$$
Finally, we set the delimiter back to a semi-colon:

DELIMITER ;
The AFTER UPDATE trigger is almost identical:

DELIMITER $$

CREATE
 TRIGGER `blog_after_update` AFTER UPDATE 
 ON `blog` 
 FOR EACH ROW BEGIN
 
  IF NEW.deleted THEN
   SET @changetype = 'DELETE';
  ELSE
   SET @changetype = 'EDIT';
  END IF;
    
  INSERT INTO audit (blog_id, changetype) VALUES (NEW.id, @changetype);
  
    END$$

DELIMITER ;
It’s beyond the scope of this article, but you could consider calling a single stored procedure which handles both triggers.

Trigger Happy?

Let’s see what happens when we insert a new post into our blog table:

INSERT INTO blog (title, content) VALUES ('Article One', 'Initial text.');
A new entry appears in the `blog` table as you’d expect:
idtitlecontentdeleted
1Article OneInitial text0
In addition, a new entry appears in our `audit` table:
idblog_idchangetypechangetime
11NEW2011-05-20 09:00:00
Let’s update our blog text:

UPDATE blog SET content = 'Edited text' WHERE id = 1;
As well as changing the post, a new entry appears in the `audit` table:
idblog_idchangetypechangetime
11NEW2011-05-20 09:00:00
21EDIT2011-05-20 09:01:00
Finally, let’s mark the post as deleted:

UPDATE blog SET deleted = 1 WHERE id = 1;
The `audit` table is updated accordingly and we have a record of when changes occurred:
idblog_idchangetypechangetime
11NEW2011-05-20 09:00:00
21EDIT2011-05-20 09:01:00
31DELETE2011-05-20 09:03:00

This is a simple example but I hope it’s provided some insight into the power of MySQL triggers.

Friday, February 6, 2015

Computer Science MCQ's

Computer Science MCQ's

http://www.indiabix.com/computer-science/computer-fundamentals/

http://www.indiabix.com/computer-science/networking/

Saturday, January 31, 2015

Submit ajax request on same page


if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
        //fun goes here.
}

Wednesday, January 28, 2015

Create a CSV File for a user in PHP

An improved version of the function from php.net

function download_csv_results($results, $name = NULL)
{
    if( ! $name)
    {
        $name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';
    }
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename='. $name);
    header('Pragma: no-cache');
    header("Expires: 0");
    $outstream = fopen("php://output", "w");
    fputcsv($outstream, array_keys($results[0])); //This will  include column headers
    foreach($results as $result)
    {
        fputcsv($outstream, $result);
    }
    fclose($outstream);
}

    require_once("yourdatabaseconnection.php");  //Include your database connection here
    $sql = mysql_query("SELECT * FROM your_table'") or die(mysql_error()); 


    if(mysql_num_rows($sql) > 0)
    {
        $results = array();
        while($rows = mysql_fetch_assoc($sql)){
            $results[] = $rows;   
        }

      //call your function here
       download_csv_results($results, 'your_file_name_here.csv');    }

Tuesday, January 20, 2015

Free jQuery/Javascript Data Grid Plugins

Sigma Grid

Sigma Grid Written in pure javascript, Sigma grid is an open source AJAX data grid for displaying and inline editing data in a scrollable and sortable table. It is very powerful yet  easy to use &  integrate with php, asp.net, jsp and RoR.
Sigma Ajax Grid -- Ajax editable data grid
Sigma Ajax Grid -- Ajax editable data grid

jQuery Grid

jqGrid is a grid component for ASP.NET & PHP based on the world’s most popular and flexible jQuery grid plugin jqGrid.
lexible jQuery grid plugin jqGrid
lexible jQuery grid plugin jqGrid

jqGridView

jqGridView is new, client-rich, XML-based, ajax grid plugin for jQuery library. jqGridView provides professional solution for representing and editing tabular data on the web. Carefully designed, with powerful script API, this editable DHTML grid is easy configurable with XML, and shows convincing results working with large amounts of data. jqGridView allows easy implementation of nice looking(managed through css). jqGridView is not platform-depending plug-in, it can be used with different web -programming platforms like: ASP .NET/ASP, PHP, JAVA, CGI scripts etc. jqGridView has hight bowser compatibility.

Ingrid

Ingrid is an unobtrusive jQuery component that adds datagrid behaviors (column resizing, paging, sorting, row and column styling, and more) to your tables. It’s easy to get started – read on below, or check out theExample Pages.
Ingrid is an unobtrusive jQuery component
Ingrid is an unobtrusive jQuery component

DataTable

DataTable is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.
DataTables is a plug-in for the jQuery Javascript library
DataTables is a plug-in for the jQuery Javascript library

Slickgrid

Slickgrid Quite simply, SlickGrid is a JavaScript grid/spreadsheet component.
It is an advanced component and is going to be a bit more difficult to learn and configure, but once you realize its full potential, it will blow your mind!
Some highlights:
  • Adaptive virtual scrolling (handle hundreds of thousands of rows with extreme responsiveness)
  • Extremely fast rendering speed
  • Supports jQuery UI Themes
  • Background post-rendering for richer cells
  • Configurable & customizable
  • Full keyboard navigation
  • Column resize/reorder/show/hide
  • Column autosizing & force-fit
  • Pluggable cell formatters & editors
  • Support for editing and creating new rows.
  • Grouping, filtering, custom aggregators, and more!
  • Advanced detached & multi-field editors with undo/redo support.
  • “GlobalEditorLock” to manage concurrent edits in cases where multiple Views on a page can edit the same data.

TableSorter

Tablesorter is a jQuery plugin for turning a standard HTML table with THEAD and TBODY tags into a sortable table without page refreshes. tablesorter can successfully parse and sort many types of data including linked data in a cell. It has many useful features including:
  • Multi-column sorting
  • Parsers for sorting text, URIs, integers, currency, floats, IP addresses, dates (ISO, long and short formats), time. Add your own easily
  • Support secondary “hidden” sorting (e.g., maintain alphabetical sort when sorting on other criteria)
  • Extensibility via widget system
  • Cross-browser: IE 6.0+, FF 2+, Safari 2.0+, Opera 9.0+
  • Small code size

Tuesday, December 23, 2014


Ubuntu is one of the most popular forms of the Linux operating system. It is available for free, and will run on almost any computer. This guide will show you how to install Ubuntu by booting from a CD or within Windows itself.

Method 1 of 2: Installing From CD/DVD

  1. 1
    Download the Ubuntu ISO file. You can get the ISO file from the Ubuntu website. An ISO file is a CD image file that will need to be burned before you can use it. There are two options available from the Ubuntu website (you can also buy official Ubuntu CDs, which come in packs of 10):
    • 14.04 LTS has continuous updates and provides technical support. It is scheduled to be supported until April 2019. This option will give you the most compatibility with your existing hardware.
      Install Ubuntu Linux Step 1Bullet1.jpg
    • Ubuntu builds (not yet released) 14.10, 15.04, and 15.10 will come with limited support. They will have the newest features, though they may not work with all hardware. These releases are geared more towards experienced Linux users.
      Install Ubuntu Linux Step 1Bullet2.jpg
    • If you have a Windows 8 PC or a PC with UEFI firmware, download the 64-bit version of Ubuntu. Most older machines should download the 32-bit version.
      Install Ubuntu Linux Step 1Bullet3.jpg
    Ad
  2. Install Linux Step 1Bullet2.jpg
    2
    Burn the ISO file. Open up your burning program of choice. There are free and paid programs available that can burn an ISO to a CD or DVD.
  3. Install Linux Step 2Bullet3.jpg
    3
    Boot from the disc. Once you have finished burning the disc, restart your computer and choose to boot from the disc. You may have to change your boot preferences by hitting the Setup key while your computer is restarting. This is typically F12, F2, or Del.
  4. Install Ubuntu Linux Step 4 Version 2.jpg
    4
    Try Ubuntu before installing. Once you boot from the disc, you will be given the option to try Ubuntu without installing it. The operating system will run from the disc, and you will have a chance to explore the layout of the operating system.
    • Open the Examples folder to see how Ubuntu handles files and exploring the operating system.
      Install Ubuntu Linux Step 4Bullet1.jpg
    • Once you are done exploring, open the Install file on the desktop.
      Install Ubuntu Linux Step 4Bullet2.jpg
  5. Install Ubuntu Linux Step 5.jpg
    5
    Install Ubuntu. Your computer will need at least 4.5 GB of free space. You will want more than this if you want to install programs and create files. If you are installing on a laptop, make sure that it is connected to a power source, as installing can drain the battery faster than normal.
    • Check the “Download updates automatically” box, as well as the “Install this third-party software” box. The third-party software will allow you to play MP3 files as well as watch Flash video (such as YouTube).
      Install Ubuntu Linux Step 5Bullet1.jpg
  6. Install Ubuntu Linux Step 6.jpg
    6
    Set up the wireless connection. If your computer is not connected to the internet via Ethernet, you can configure your wireless connection in the next step.
    • If you didn’t have an internet connection in the previous step, hit the Back button after setting up the wireless connection so that you can enable automatic updates.
  7. 7
    Choose what to do with your existing operating system. If you have Windows installed on your system, you will be given a couple options on how you’d like to install Ubuntu. You can either install it alongside your previous Windows installation, or you can replace your Windows installation with Ubuntu.
    • If you install it alongside your old version of Windows, you will be given the option to choose your operating system each time you reboot your computer. Your Windows files and programs will remain untouched.
      Install Ubuntu Linux Step 7Bullet1.jpg
    • If you replace your installation of Windows with Ubuntu all of your Windows files, documents, and programs will be deleted.
      Install Ubuntu Linux Step 7Bullet2.jpg
  8. Install Ubuntu Linux Step 8.jpg
    8
    Set your partition size. If you are installing Ubuntu alongside Windows, you can use the slider to adjust how much space you would like to designate for Ubuntu. Remember that Ubuntu will take up about 4.5 GB when it is installed, so be sure to leave some extra space for programs and files.
    • Once you are satisfied with your settings, click Install Now.


      Install Ubuntu Linux Step 8Bullet1.jpg
  9. Install Ubuntu Linux Step 9.jpg
    9
    Choose your location. If you are connected to the internet, this should be done automatically. Verify that the timezone displayed is correct, and then click the Continue button.
  10. Install Ubuntu Linux Step 10 Version 2.jpg
    10
    Set your keyboard layout. You can choose from a list of options, or click the Detect Keyboard Layout button to have Ubuntu automatically pick the correct option.
  11. Install Ubuntu Linux Step 11 Version 2.jpg
    11
    Enter your login information. Enter your name, the name of the computer (which will be displayed on the network), choose a username, and come up with a password. You can choose to have Ubuntu automatically log you in, or require your username and password when it starts.
  12. Install Ubuntu Linux Step 12 Version 2.jpg
    12
    Wait for the installation process to complete. Once you choose your login info, the installation will begin. During setup, various tips for using Ubuntu will be displayed on the screen. Once it is finished, you will be prompted to restart the computer and Ubuntu will load.

Method 2 of 2: Using the Windows Installer

  1. Install Ubuntu Linux Step 13.jpg
    1
    Download the installer from the Ubuntu website. If your browser prompts you, select Run, Save, or Open. The Windows installer is not compatible with Windows 8. You must use the method in the previous section.
    • The Windows installer will install Ubuntu alongside Windows. Your files and programs will not be affected. When you reboot your computer, you will be able to choose which operating system you would like to load.
      Install Ubuntu Linux Step 13Bullet1.jpg
  2. Install Ubuntu Linux Step 14.jpg
    2
    Choose your username and password. Once you run the installer, you will be presented with the configuration menu. Choose your new Ubuntu username and password.
    • You can also change the size of the Ubuntu installation. A larger installation will give your Linux operating system more space to install programs and add files, but this will take away from the free space that Windows has access to.
      Install Ubuntu Linux Step 14Bullet1.jpg
    • You can choose your Desktop environment. The three most common are:
      Install Ubuntu Linux Step 14Bullet2.jpg
      • Ubuntu (the most popular) has Unity, a unique and intuitive desktop environment.
      • Kubuntu has KDE which resembles Windows
      • Xubuntu uses Xface, which is faster and good for PCs that are 2-3 years old.
      • Lubuntu uses LXDE, and can be used with very old PCs or netbooks with as little as 512MB of RAM.
  3. Install Ubuntu Linux Step 15.jpg
    3
    Click Install to start. The installer will begin downloading the files necessary to install Ubuntu on your computer. Installation will happen automatically.
    • Downloading the files can take a significant amount of time depending on your internet connection. You can use your computer while the files download in the background.
      Install Ubuntu Linux Step 15Bullet1.jpg
  4. Install Ubuntu Linux Step 16.jpg
    4
    Restart your computer. Once the installation is complete, you will be given the option to reboot now or later. When you reboot, you will see a new menu before Windows starts that allows you to choose between Windows and Ubuntu.
Note: Original Source: http://www.wikihow.com/Install-Ubuntu-Linux

IF YOU WANT TO INSTALL ON CUSTOM DRIVE THEN SKIP STEP 7 & 8 AND FOLLOW THESE STEPS:

You should install Ubuntu on a separate partition so that you won't lose any data. The most important thing is you should create a separate partition for Ubuntu manually, and you should select it while installing Ubuntu.
First create a separate partition for Ubuntu while running Windows (like a partition with more than 10 GB). Also create a small partition for the swap partition (size is equal to your RAM size).
  • You should know the partition sizes you created so that you can identify them easily while installing Ubuntu.
See the below images - I picked them by googling so they won't be same as yours (like partition sizes and number of partitions).
The second important thing is while installing Ubuntu select "Something else".
Enter image description here
It will allow you to select your manually created partition to install Ubuntu onto it.
Now select and edit the partition you created for Ubuntu. Be careful in selecting. Check twice that you selected the correct partition, not some other partition as you may lose data like before.
Enter image description here
Select the format partition, use as mount point as shown in the image. The size is up to you.
After that, select the swap partition, and edit it as shown in the image (size is your choice).
Enter image description here
After that select the "Device for boot loader installation" at the bottom and select the one with /dev/sda at the beginning.
Enter image description here
Now you can select "install now" at the right bottom.
It seems lengthy, but it's really easy once you know this installation.

How to change the PHP version for subfolders or subdomains

  How to change the PHP version for subfolders or subdomains Setting a specific PHP version for a specific websites, subfolders or subdomain...