My Google+ Profile

Friday 28 December 2012

Why Yii Framework become more Popularity?

What is new feature of Yii? Why is it becoming so popular among developers today?

Yii (acronym for ‘Yes It Is!’) is a component-based PHP framework with high performance level that best fits for developing Web applications of large scale. Yii comes with a full pack of features covering DAO/ActiveRecord, MVC, caching, I18N/L10N, jQuery-based AJAX support, authentication and role-based access control, input validation, scaffolding, events, widgets, Web services, theming etc.

Yii was created for web programming of general purpose which can be used for development of basically any sort of web applications. Thanks to the presence of the powerful caching tool, Yii is particularly effective for rapid applications development with a big traffic flow such as forums, CMS, portals, eCommerce systems etc. It is known for its flexibility, usability and high speed. Among its other advantages Yii supports modules, components and widgets as well as integrates with JavaScript framework jQuery. It can also be utilized either as Active Record or as Data Access Objects. In addition Yii has a convenient web-based code generator called Gii and there is a command line interface for some operations like DB migrations.

Yii is written using OOP principles and therefore it is very flexible and extensive as well as it is easy to use. Yii has a large community and as a result a lot of solutions in the form of extensions. There is good support with an ability to offer changes and improvements on Github. Moreover, Yii has publicly available excellent documentation.

Many developers, after having dealt with Yii are left totally impressed by the framework. Lots of them agree that the learning curve is pretty short thanks to its ability to eliminate duplicating code and automatic adapting to the database changes. Security issues are also taken care of due to the input validation functionality of CModel and the usage of PDO and parameter binding by CActive Record and making the operations safe by default.

You can see the comparison at http://www.phpframeworks.com/top-10-php-frameworks with other popular frameworks, Yii holds the highest positions.

Friday 21 December 2012

Multi-language site in yii framework

To make multi language in your yii framework you have to implements some rules. You can use the session variables to make the translation between your page. With the the documentation you can look at here.

I have to implements this to make the translation page. You can follow the instruction in that articles that not almost I discuss in this page.

But when I finish implement that step, I can make my own translation page on the protected/messages/<your language id>/<your category>.php files..

For the example :

../protected/messages/id/translation.php

The example of the translation page that I use like this

<?php
/**
 * Indonesian translate
 */
return array(
  //------MENU------------//
  'Home'=>'Beranda',
  'About'=>'Tentang',
  'Contact'=>'Kontak',
  'Login'=>'Masuk',
  'Logout'=>'Keluar',
   
   
   
  //----------- Other Example ------------------//
  'What are You Looking For?'=>'Apa Yang Anda Cari?',
  'Sell Your Products'=>'Mau Menjual Barang',
  'Products'=>'Barang',
  'Services'=>'Jasa'
   
  );
?>


Oke when you finish that I use my native languages (Indonesian=ID) and than I can use that for my translation in my code using this example in your view files.

echo Yii::t('translation','Home');

Wednesday 19 December 2012

Drupal 7 - The basic way of using the Colorbox module

This article is about the usage of Jquery Colorbox Plugin, which most of you must be either accustomed to or at least heard of. This post is aimed at those who know about the module, but still haven’t made the use of it. So, here’s what to begin with.

The Colorbox module is a light-weight as well as customizable lightbox plugin for jQuery 1.3 through 1.6. When it comes to Drupal 7, the colorbox jquery plugin is integrated with a module Colorbox. The usage of this module facilitates the display of images, iframed or inline content etc. in an overlay above the current page.

Features of the Colorbox module

Let’s take a brief look at the various features of the Colorbox module. The following are a list of its features:
  1. Outstanding integration with Imagefield Imagecache, Insert and  Image modules.
  2. A variety of choice is available between a default style and a number of other styles that are included.
  3. The facility of styling the Colorbox with a custom Colorbox style in your theme is also present.
  4. There’s an option to open a login form by clicking on any login link
  5. Drush command is available to download and install the Colorbox plugin in sites/all/libraries as well as a Drush make file

Features of the Colorbox plugin:

  • Supports images, image groups, slideshow, ajax, inline, and iframed content.
  • Preloads background images and can preload upcoming images in a photo group.
  • Appearance is controlled through CSS so users can restyle the box.

Showing content images in Colorbox

Having discussed the features of the module, let’s move on to make use of the Colorbox module in order to show content images in a colorbox.

Step: 1

Download the Colorbox module from drupal.org and place it in sites/all/modules folder.

Step: 2

Now, go to modules and then enable the Colorbox module.

Step: 3

Download and unpack the Colorbox plugin in “sites/all/libraries”.
Link: http://colorpowered.com/colorbox/colorbox.zip
The Drush users can use the command “drush colorbox-plugin”.

Step: 4 

You’ll have to add 2 new presets by clicking on configuration-> Media ->Image Styles.
Set the height and width of the presets according to your requirements.
While one preset will be used for the purpose of preview image, the other one will be use for the full image to be shown on colorbox.
Save both the image styles.

Step: 5

Now, create a new content type, and then add an image field to it.
Select the image preview style name we just created in the image styles. Here we will use the smaller image to be shown on the listing page. Click on the save option.
Add some images to the new content type we just created.

Step: 6

After this, create a view and give it a name and continue with the default settings.
Apply the filter criteria by choosing the content name as the filter.
Now select fields to display in the view.

Step: 7

Select Content Title and Content : Image Field Name as the fields.
In the Image Field Name settings page enter a label name for the field.

Step: 8

Now, from the Formatter dropdown select the Colorbox option.
In the Node Image Style choose the name of the image style we created. Remember to use the smaller size for this field.

Step: 9

In the Colorbox Image Style select the name of bigger image style.
Click save and save the views also.

Step: 10

Here, go back to the content type we have just created and then,

Click on Manage Display Field.

Next to Image field you’ll be able to notice a dropdown menu labeled as Format.

Select Colorbox and configure the settings for the field.
 
Node Image Style: Smaller Image style.
Colorbox Image Stye: Large Image Style.

All done, now click on Save.

After following all the above mentioned steps, you should be able to see your images in a colorbox by clicking on them.

You can also choose to use the Colorbox Stylesheets. All you have to do is to simply copy the whole folder into your theme folder and then include it into your template files.

The Colorbox plugin is very useful and we can do a lot of things with the images with the help of this module. Hope we were able to deliver the idea of the basic stuff to begin with through this post.

Sunday 16 December 2012

8 Tips for Drupal Usability

Usability is not a big problem to talk a lot about it in the Drupal community. But it makes Drupal services more comfortable for users and we still try to make Drupal sites as usable as possible. Fortunately there are a lot of simply tools you can use to make your life easier.
Let’s give you some simple tips how to improve the usability of Drupal.

Build your own admin dashboard

There are a lot of experimental modules to build it. You may have Wordpress like a dashboard screen for admin. Using Panels can be very useful.

Many users don’t understand multiple select boxes

Probably most of the people know that in order to select multiple options in a select box you may use Ctrl+Click. But many people do not aware of it. They think it is rather to use checkboxes instead.

Disable all distractions which the user doesn’t need

Of course, Drupal provides a lot of useful functions but don’t give to your visitors the information which is not useful for them.

Show the results

Drupal doesn’t automatically display the number of search results. But you can add this functionality to make a big help for your visitors.

Make your node-edit screen

In order to make your node-edit screen more usable you can use Drupal 6 module. Then vertical tabs will make your node edit screen less cluttered.

Redirect visitors to the right place

You need to separate admin roles and task for administrators to send users directly to the specific page. In order to do it you can use Rules or the core trigger module. The last one has more features.

Use Diff module to see the differences are made

Diff module is pretty useful with revision option for nodes. So you can use it to see any changing is made.

Taxonomy

Taxonomy can be a little confused for some users. You may have hierarchical select steps in as an option and it could automatically control it. Also it enables selection methods through jQuery to find a lot of scalable solutions.

Monday 10 December 2012

Tree structure in Dropdown using Yii

In this tutorial, we create tree structure dropdown list like as below :-

RHCE
--SE1
RHCSA
--SA1
--SA2
PHP

Table strucure for this kind of tree is as below :
id parent_id course_name
1     0               RHCE
2     0               RHCSA
3     1               SE1
4     2               SA1
5     2              SA2
6     0              PHP

I have create class file in component folder because i can use it anywhere in my application but you can create this file's function anywhere.

In components folder create a new class CommonMethods.

<?php
/*
* /protected/components/CommonMethods.php

 */
class CommonMethods {
 
    private $data = array();
   
    public function makeDropDown($parents)
    {
        global $data;
        $data = array();
        $data['0'] = '-- ROOT --';
        foreach($parents as $parent)
        {
           
                $data[$parent->id] = $parent->name;
                $this->subDropDown($parent->children);
               
        }
       
       return $data;
    }
   
  public function subDropDown($children,$space = '---')
    {
        global $data;
       
        foreach($children as $child)
                {
                   
                        $data[$child->id] = $space.$child->name;
                        $this->subDropDown($child->children,$space.'---');
                }
       
    }
   
   
}
?>

In you model make relations.
public function relations()
{
                  return array(

                    'parent' => array(self::BELONGS_TO, 'CourseMaster', 'parent_id', 'condition' => 't.parent_id <> 0'),

                    'children' => array(self::HAS_MANY, 'CourseMaster', 'parent_id'),

               );

}

In your view _form.php
    <div class="row">

       <?php


          $parents = CourseMaster::model()->findAll('parent_id = 0');
 $cm = new CommonMethods();

          $data = $cm->makeDropDown($parents);


          echo $form->labelEx($model,'parent_id');

          echo $form->dropDownList($model,'parent_id',  $data);


      ?>


    </div>

Thursday 6 December 2012

PHP mysql_real_escape_string() Function to prevent MySQL - SQL Injection Prevention

What is SQL Injection

SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

SQL Injection Example

Below is a sample string that has been gathered from a normal user and a bad user trying to use SQL Injection. We asked the users for their login, which will be used to run a SELECT statement to get their information.

MySQL & PHP Code:

// a good user's name
$name = "timmy"; 
$query = "SELECT * FROM customers WHERE username = '$name'";
echo "Normal: " . $query . "<br />";

// user input that uses SQL Injection
$name_bad = "' OR 1'"; 

// our MySQL query builder, however, not a very safe one
$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";

// display what the new query will look like, with injection
echo "Injection: " . $query_bad;

Display:

Normal: SELECT * FROM customers WHERE username = 'timmy'
Injection: SELECT * FROM customers WHERE username = '' OR 1''



The normal query is no problem, as our MySQL statement will just select everything from customers that has a username equal to timmy.
However, the injection attack has actually made our query behave differently than we intended. By using a single quote (') they have ended the string part of our MySQL query
  • username = ' '
and then added on to our WHERE statement with an OR clause of 1 (always true).
  • username = ' ' OR 1
This OR clause of 1 will always be true and so every single entry in the "customers" table would be selected by this statement!


More Serious SQL Injection Attacks


Although the above example displayed a situation where an attacker could possibly get access to a lot of information they shouldn't have, the attacks can be a lot worse. For example an attacker could empty out a table by executing a DELETE statement.

MySQL & PHP Code:

$name_evil = "'; DELETE FROM customers WHERE 1 or username = '"; 

// our MySQL query builder really should check for injection
$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";

// the new evil injection query would include a DELETE statement
echo "Injection: " . $query_evil;

Display:

SELECT * FROM customers WHERE username = ' '; DELETE FROM customers WHERE 1 or username = ' ' 

If you were run this query, then the injected DELETE statement would completely empty your "customers" table. Now that you know this is a problem, how can you prevent it?

Injection Prevention - mysql_real_escape_string()

Lucky for you, this problem has been known for a while and PHP has a specially-made function to prevent these attacks. All you need to do is use the mouthful of a function mysql_real_escape_string.
What mysql_real_escape_string does is take a string that is going to be used in a MySQL query and return the same string with all SQL Injection attempts safely escaped. Basically, it will replace those troublesome quotes(') a user might enter with a MySQL-safe substitute, an escaped quote \'.
Lets try out this function on our two previous injection attacks and see how it works.

MySQL & PHP Code:

//NOTE: you must be connected to the database to use this function!
// connect to MySQL

$name_bad = "' OR 1'"; 

$name_bad = mysql_real_escape_string($name_bad);

$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";
echo "Escaped Bad Injection: <br />" . $query_bad . "<br />";


$name_evil = "'; DELETE FROM customers WHERE 1 or username = '"; 

$name_evil = mysql_real_escape_string($name_evil);

$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";
echo "Escaped Evil Injection: <br />" . $query_evil;

Display:

Escaped Bad Injection:
SELECT * FROM customers WHERE username = '\' OR 1\''

Escaped Evil Injection:
SELECT * FROM customers WHERE username = '\'; DELETE FROM customers WHERE 1 or username = \''

Notice that those evil quotes have been escaped with a backslash \, preventing the injection attack. Now all these queries will do is try to find a username that is just completely ridiculous:
  • Bad: \' OR 1\'
  • Evil: \'; DELETE FROM customers WHERE 1 or username = \'
And I don't think we have to worry about those silly usernames getting access to our MySQL database. So please do use the handy mysql_real_escape_string() function to help prevent SQL Injection attacks on your websites. You have no excuse not to use it after reading this lesson!



Monday 3 December 2012

Search functionality on an index page

Here's how to implement simple and easy search functionality on an index page:

1. Let's say your controller looks like this:
public function actionIndex()
{
  $dataProvider=new CActiveDataProvider('Model');
  $this->render('index',array(
  'dataProvider'=>$dataProvider,
  ));
}
2. Change it to this:
public function actionIndex()
{
    $criteria = new CDbCriteria();

    if(isset($_GET['q']))
    {
      $q = $_GET['q'];
      $criteria->compare('attribute1', $q, true, 'OR');
      $criteria->compare('attribute2', $q, true, 'OR');
    }

    $dataProvider=new CActiveDataProvider
            ("Model", array('criteria'=>$criteria));

    $this->render('index',array(
      'dataProvider'=>$dataProvider,
    ));
}
The above will read in the "q" (for query) parameter, and use the compare function to create the sql to search a few attributes for that value. Note the use of the 'OR' operator.

3. In your index view, add this:
<form method="get">
<input type="search" placeholder="search" name="q" 
value="<?=isset($_GET['q']) ? CHtml::encode($_GET['q']) : '' ; 
?>" />
<input type="submit" value="search" />
</form>
The above creates a form that will submit to itself using the querystring. It displays a search input box, which is a text input box with a "cancel" command. It works in most browsers and defaults to a text field in the rest. When the user hits the search button, the form is submitted and the data is filtered by the search value.

Snapshot:

Get all sunday date of current Year Using PHP

Following function return array of list of Sunday's Date of the Current Year in PHP.

<?php

function getDateForSpecificDayBetweenDates($startDate, $endDate, $weekdayNumber)
{
    $startDate = strtotime($startDate);
    $endDate = strtotime($endDate);

    $dateArr = array();

    do
    {
        if(date("w", $startDate) != $weekdayNumber)
        {
            $startDate += (24 * 3600); // add 1 day
        }
    } while(date("w", $startDate) != $weekdayNumber);


    while($startDate <= $endDate)
    {
        $dateArr[] = date('Y-m-d', $startDate);
        $startDate += (7 * 24 * 3600); // add 7 days
    }

    return($dateArr);
}

$year   = date("Y");

$dateArr = getDateForSpecificDayBetweenDates($year.'-01-01', $year.'-12-31', 0);

print "<pre>";
print_r($dateArr);

?>

And if you want to get any other day of  week then just change value of weekday. I have pass 0 value into the function to get all Sunday of the current year.

Note : Pass weekdays value between 0  to 6. 

Tuesday 27 November 2012

6 Steps to Create a Successful Website

Creating website is very important and responsible task. You need to take into account all the main moments to make it user-friendly and informative. We want to share with you stages cover website design and development processes.


Background Information

First of all, you need to know for sure the purpose of your website. Very often people think they defined with a choice when at the last moment generate new idea for new site. There are the main moments to be considered:
  • know the main purpose of your website: service promotion, providing information to visitors, products selling, etc.;
  • define what you are going to gain from the site and what you want to accomplish: your goals (make money, share information);
  • detect the target audience: try to imagine the “ideal” person who will visit your site (age, sex, interests); this will help you when you’ll be choosing content for your site.

 

Make a Plan

This is a second but very important stage. It’s time for writing site map (a list that includes the main topics and sub-topics). Designers and developers select the main tools that will be used for building your site depending on its purpose and target customers.

 

Design Process

Designers of your website are preparing images of layout, interface, etc. and send you possible variants to choose the most suitable one. On this step specialists are guided by the idea of “ideal” visitor. For example, if your website will provide information for women it should have an appropriate template, maybe something in pink colors, feminine, glamour and light; in case if you aim to make something for businesses try minimalist style with classic elements, etc. Don’t forget about company logo to identify it on the site.

 

Development Process

This is a time for implementation of chosen techniques on practice and finally development of the website. Usually everything starts with creation of the Home Page. Developers follow the main navigational structure for the site – the shell for interior. On this stage you still can make and corrections or additional changes.

 

Testing and Delivering Processes

This is very important, but unfortunately often overlooked step. Before launching your website you need to be sure everything works as intended. For this purpose experts make functional, usability and other types of testing, examine the codes to prevent any risks associated with vulnerabilities. Web designers use FTP or CMS to upload files into the website, index it and ensure that site operates correctly and users can visit it through the various browsers.

 

Maintenance

Creation and launching the website is only beginning. Whether you ordered development of the website or made it by yourself you need to update the content frequently, add some information or make corrects. Most of designers will be happy to continue work with your site. If you aim to increase the search engine ranking you better hire SEO-optimizer, copywriter, etc.
So, what useful information you can extract from this article? There are the main 6 steps of website creation. It is not easy to put it on practice, you need to figure out many aspects before starting to provide the project with succeed implementation.

Saturday 24 November 2012

Date validation in Yii

The date validator CDateValidator was added to Yii in release 1.1.7 and provides an easy method to validate that a field contains a date, time or datetime, with the following parameters.

format - option enables you to specify the date format or a list of date formats in an array.

allowEmpty - whether to allow empty or null values

for example:

public function rules()
{
return array(
           // multiple formats specified to allow for 01/02/20012 and 1/02/2012
           array('experience_from, experience_to ', 'date', 'format'=>array('dd/MM/yyyy','d/MM/yyyy'), 'allowEmpty'=>true),
           array('created_dt, last_updated, ', 'date', 'format'=>'yyyy-MM-dd HH:mm:ss', 'allowEmpty'=>false),
  );
}


So now we can be sure that the user has input valid date formats – what about date ranges.

If we wanted to check that the experience_to is greater than the experience_from we could perhaps use the compare validator for date ranges as follows:

  array('experience_to','compare','compareAttribute'=>'experience_from','operator'=>'>', 'allowEmpty'=>true,'message'=>'{attribute} must be greater than "{compareValue}".')


So, wouldn’t life be nice and easy if this code worked …. but it doesn’t!

The date comparison validator uses datetimestamps.  It does not convert textual dates into timestamps.  Therefore the date in the format “dd/mm/yyyy” of 16/01/2012 is greater than 10/02/2012.

It looks as though we will still need to build a custom function to convert these dates to datetimestamps first and then do the comparison test.

So here is date function to do that validation.

        public function dateCompare($attribute,$params) {

            if (empty($params['compareAttribute']) || empty($params['operator']))
               $this->addError($attribute, 'Invalid Parameters to dateCompare');

            $compareTo=$this->$params['compareAttribute'];

            if($params['allowEmpty'] && (empty($this->$attribute) || empty($compareTo)))
        return;

            //set default format if not specified
            $format=(!empty($params['format']))? $params['format'] : 'dd/MM/yyyy';
            //default operator to >
            $compare=(!empty($params['operator'])? $params['operator'] : ">";

            $start=CDateTimeParser::parse($this->$attribute,$format);
            $end=CDateTimeParser::parse($compareTo,$format);
            //a little php trick - safe than eval and easier than a big switch statement
            if (version_compare($start,$end,$compare)) {
                    return;
            } else {
                    $this->addError($attribute, "start date is not $compare end date");
            }
        }

and then we can change the validation rules as follows:

{
return array(
           array('experience_from, experience_to ', 'date', 'format'=>array('dd/MM/yyyy','d/MM/yyyy'), 'allowEmpty'=>true),
           array('created_dt, last_updated, ', 'date', 'format'=>'yyyy-MM-dd HH:mm:ss', 'allowEmpty'=>false),
           array('experience_to','dateCompare','compareAttribute'=>experience_from','operator'=>'>', 'allowEmpty'=>true),
  );
}

Thanks.

Export to excel CGridview filtered/shorted record in Yii.



Recently, i have find an issue to export CGridview filtered record in excel in my Yii application. I have searching out lot many thigs but i did not get exact solution which i want. In all reference tutorial, i can export CGridview record without filtered or shorted record.

Finally i got one solution to export filtered CGridview record to excel using session and toexcel extension of Yii. You can see in following search method, I have stored filtered record in session variable and return it. So whenever i will search any record details it will store in session variable. And later, i will use that session variable to export action.

    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('nationality_id',$this->nationality_id);
        $criteria->compare('nationality_name',$this->nationality_name,true);
        $criteria->compare('nationality_organization_id',$this->nationality_organization_id);
        $criteria->compare('nationality_created_by',$this->nationality_created_by);
        $criteria->compare('nationality_created_date',$this->nationality_created_date,true);

        $nationality_data = new CActiveDataProvider(get_class($this), array(
            'criteria'=>$criteria,
        ));
       
        $_SESSION['nationality_records'] = $nationality_data;
        return $nationality_data;
    }

Here, Assign CActiveDataProvider data to session variable.

    public function actionNationalityExportToExcel()
    {
        $this->toExcel($_SESSION['nationality_records'],
        array(
            //'nationality_id::SN',
            'nationality_name',
            'Rel_user.user_organization_email_id',
            'Rel_org.organization_name',
       
        ),
        'Nationality',
        array(
            'creator' => 'RudraSoftech',
        ),
        'Excel2007'
        );
    }

Note : Also go throw the toexcel extension and put require class file in extension folder directory.

Using this extension you can export data in excel in multiple excel version format like 2005 and 2007.

Static Radio Button List in Yii

Generate RadioButtonList

The following code:

echo CHtml::RadioButtonList('id', '', array('student'=>'Student','employee'=>'Employee'));

will generate:

<input value="student" id="id_0" type="radio" name="id">
<label for="id_0">Student</label>
<br>
<input value="employee" id="id_1" type="radio" name="id">
<label for="id_1">Employee</label>

Other tricks:

Display them inline without '<br>' separator:


echo CHtml::RadioButtonList('id', '', array('student'=>'Student','employee'=>'Employee'), 
array('labelOptions'=>array('style'=>'display:inline'), separator'=>''));

Thursday 6 September 2012

User Authentication using crypt (salt) encryption method in Yii

First of all you need to create user table model,view and controller for user authetication and authorization. And then you need to encrypt password using crypt() method at the time of creation of new user. You can convert password like this.

UserController.php

    public function actionCreate()
    {
        $model=new User;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['User']))
        {
            $model->attributes=$_POST['User'];
          
            $model->password = crypt($model->password);

            if($model->save())
                $this->redirect(array('view','id'=>$model->user_id));
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }

Note: crypt() function return different crypted string everytime. so you need to make following change to compare your password with crypted password in Yii.


UserIdentity.php


public $_id;
public function authenticate()
{
              $record=User::model()->findByAttributes(array('username'=>$this->username));
        if($record===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        else if($record->password!==crypt($this->password,$record->password))
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        else
        {
            $this->_id=$record->user_id;
            $this->errorCode=self::ERROR_NONE;
        }
        return !$this->errorCode;
        }
  
        public function getId()
        {
        return $this->_id;
        }
}

Monday 30 July 2012

Use single(common) database in development environment Yii framework.

Please follow following steps:

step 1 : Add new user in your mysql database privileges options. You will get following window to add new user.







step 2 : Make following changes in mysql config file name my.conf(Ubuntu OS).

    From :
    bind-address           = 127.0.0.1

    To:
    bind-address           = *

    NOTE : my.conf file exist in ubuntu at this location : /etc/mysql/my.cnf

step 3 : Finally restart mysql service by following ubuntu command.
  
    /etc/init.d/mysql restart

step 4 : Make following changes in config.php file

        'db'=>array(
            'connectionString' => 'mysql:host=NETWORK_DESKTOP_IP;dbname=DATABASE_NAME',
            'emulatePrepare' => true,
            'username' => 'USERNAME',
            'password' => 'PASSWORD',
            'charset' => 'utf8',
        ),
      

  
  
       

Monday 23 April 2012

This article is used for upload multiple files and moved them to particular folder and stored that folder path location into database table in Yii application.

First of all, Make following changes to your model file.

model.php

    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('image', 'required'),
//            array('image', 'length', 'max'=>300),
            array('image', 'file', 'types'=>'jpeg, gif, png'),
   
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, image', 'safe', 'on'=>'search'),
        );}


Then, Make this changes in view file.


_form.php


    <div class="row">
        <?php echo $form->labelEx($model,'image'); ?>
        <?php $this->widget('CMultiFileUpload', array(
                'name' => 'image123',
        'model'=>$model,
            'attribute'=>'image',
        'accept' => 'jpeg|jpg|gif|png', // useful for verifying files
                'duplicate' => 'Duplicate file!', // useful, i think
                'denied' => 'Invalid file type', // useful, i think
            ));
        ?>
    </div>

Make following changes to your controller.

controller.php

    public function actionCreate()
    {
        $model=new PhotoUploadTable;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        $images = CUploadedFile::getInstancesByName('image');

        if($images != null)
        {
                       if(isset($_POST['PhotoUploadTable']))$model->attributes=$_POST['PhotoUploadTable'];
            foreach($images as $list=>$pic)            {
               $model->setIsNewRecord(true);
              $model->id=null;
             $model->image = $pic;  
             $model->save();
             $model->image->saveAs(Yii::getPathOfAlias('webroot').'/images/' .$model->image);

            }
                $this->redirect(array('index'));
          
        }

        $this->render('create',array(
            'model'=>$model,
        ));

    }

This works perfectly for me. I hope this will help you.

Karmraj.