Codxplore.com

Latest news:

New android application Islamic Video has been released. its a free islamic video application for android smartphone. Download now!

How to run foreach loop between 2 given dates ?



$begin = new DateTime( '2010-05-01' );
$end = new DateTime( '2010-05-10' );

$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

foreach ( $period as $dt )
  echo $dt->format( "l Y-m-d H:i:s\n" );

This will output all days in the defined period between $start and $end. If you want to include the 10th, set $end to 11th. You can adjust format to your liking. See the PHP Manual for DatePeriod.


Views: 3464

Displaying the list of months using mktime for the year



Use this:

for ($m=1; $m<=12; $m++) {
     $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
     echo $month. '
'
; }

Views: 3484

How to get the first and last days of a given month



You might want to look at the strtotime and date functions.

php

$query_date = '2010-02-04';

// First day of the month.
echo date('Y-m-01', strtotime($query_date));

// Last day of the month.
echo date('Y-m-t', strtotime($query_date));

Views: 3211

php export csv utf 8



If your generating a CSV with PHP you may have stumbled upon the same problem as me where any special character such as £ becomes ASCII in your CSV, this is because the encoding of your CSV is wrong and you will need to output your CSV in UTF8 to be able to use special ASCII characters in your document.

Using my example below you can encode UTF8 your CSV file, you will notice a header with “Content-Encoding: UTF-8” and also in the “Content-Type” header you will see an extra parameter “; charset=UTF-8”. You will also notice the weird echo “xEFxBBxBF” – this is the BOM for the UTF-8 encoding, if your not sure what this is don't worry, it will not display in your document.

Please Note! UTF-8 is not supported by Macintosh version of Excel, so you will see both the BOM and the encode characters instead of the correct character – there is no fix for this and you will have to provide a version of the CSV without special characters if you need to avoid it.

So here is my example code, this will generate a CSV file using PHP’s CSV functions and will add UTF-8 support:

 

header('Content-Encoding: UTF-8');
header("Content-type: text/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename=processed_devices.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo "xEFxBBxBF";
$fp = fopen('php://output', 'w');
$list = array(
        array('id', 'name', 'value'),
        array('1', 'brent', '12'),
        array('1', 'matt', '45'),
        array('1', 'gaz', '34'),
        array('1', 'tom', '76')
    );
foreach ($list as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);

 


Views: 3565

Yii2 - Get Current Action ID in main.php



Answer

In a layout you can access the current controller via $this->context, and so the current action id by $this->context->action->id

For reference http://stackoverflow.com/questions/28769719/yii2-get-current-action-id-in-main-php


Views: 2849

Yii2 pagination



Pagination represents information relevant to pagination of data items.

When data needs to be rendered in multiple pages, Pagination can be used to represent information such as total item count, page size, current page, etc. These information can be passed to pagers to render pagination buttons or links.

The following example shows how to create a pagination object and feed it to a pager.

Controller action:

public function actionSearch($q = '') {
        $this->layout = 'site_main';

        $q = trim($q);

        $sql = "SELECT * FROM
(select p.product_id as 'sid',p.name_en,p.name_ar,p.description_en,description_ar,p.image, 'product' as 'type', 'none' as 'category_type'
from tbl_products p
union
select sl.service_location_id as 'sid' ,sl.name_en,sl.name_ar,sl.description_en,sl.description_ar,sl.image,'servicelocation' as 'type' ,'none' as 'category_type'
from tbl_service_locations sl
)
as search
WHERE search.name_en LIKE '$q%' or search.name_ar LIKE '$q%' or search.description_en LIKE '$q%' or search.description_ar LIKE '$q%'  
";
        $query = Yii::$app->db->createCommand($sql)->queryAll();

        $count = sizeof($query);

        //echo $count;

        $dataProvider = new SqlDataProvider([
            'sql' => $sql,
            'totalCount' => $count,
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);

        //$models = $dataProvider->query;

        return $this->render('search', [
                    'q' => $q,
                    'result' => $dataProvider->getModels(),
                    'dataProvider' => $dataProvider,
                    'count' => $count,
        ]);
    }

View :

foreach ($result as $row) {

 // display $model here

}

// display pagination

echo yiiwidgetsLinkPager::widget([
    'pagination' => $dataProvider->pagination,
 ]);

For reference please visit

http://www.yiiframework.com/doc-2.0/yii-data-pagination.html

 

 


Views: 3737

Yii2 leftJoin()



leftJoin()

$query = new Query;
$query    ->select(['tbl_user.username AS name', 'tbl_category.type as Category'])  
        ->from('tbl_user')
        ->leftJoin('tbl_category', 'tbl_category.createdby = tbl_user.userid')
        ->limit(2);
       
$command = $query->createCommand();
$data = $command->queryAll();


Views: 1865

Yii2 innerJoinWith()



innerJoinWith()

$model = User::find()
    ->innerJoinWith('comments', false)
    ->all();
// equivalent to the above
$model = User::find()
    ->joinWith('comments', false, 'INNER JOIN')
    ->all();

SYNTAX:

$query = new Query;
$query    ->select(['SELECT COLUMNS'])  
        ->from('TABLE_NAME_1')
        ->join(    'JOIN_TYPE',
                'TABLE_NAME_2',
                'TABLE_NAME_2.COLUMN =TABLE_NAME_1.COLUMN'
            );
$command = $query->createCommand();
$data = $command->queryAll();               

Sample 1:

$query = new Query;
$query    ->select([
        'tbl_user.username AS name',
        'tbl_category.categoryname as  Category',
        'tbl_document.documentname']
        ) 
    ->from('tbl_user')
    ->join('LEFT OUTER JOIN', 'tbl_category',
                'tbl_category.createdby =tbl_user.userid')        
    ->join('LEFT OUTER JOIN', 'tbl_document',
                'tbl_category.cid =tbl_document.did')
    ->LIMIT(5)    ;
       
$command = $query->createCommand();
$data = $command->queryAll();   


Views: 2087

Yii2 joinWith()



joinWith()

Sample 1:

$model = User::find()
    ->joinWith('comments')
    ->all();

Sample 2:

$model = User::find()
    ->joinWith('comments')
    ->orderBy('tbl_comments_id.id, tbl_user.id')
    ->all();


Views: 2022

Yii2 Relation Model



Relation Model

$model = User::find()
        ->with('comments')
        ->all();
    foreach ($model as $user) {
        // get data from relation model
        $comments = $user->comments;
        ......
        foreach($comments as $comment){
            ........
        }
    }


Views: 1237

Yii2 GridView sorting and pagination using pajax



<?php
use yiiwidgetsPjax;
?>


Add above line in the beginning of your view. 


<?php Pjax::begin(); ?>

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yiigridSerialColumn'],

        'id',
        'branch:ntext',
        'version:ntext',
        'release_date:ntext',

        [
            'class' => 'yiigridActionColumn',
            'template' => '{view}',
        ],
    ],
]); ?>

<?php Pjax::end(); ?>

 


Views: 1591

Yii2 Turning on Pretty URLs



First, let's enable Yii2's pretty URLs with mod_rewrite. On the Yii home page, if you click on the About menu option, the URL will be something like http://localhost/hello/web/index.php?r=site%2Fabout. We'd like to change that to http://localhost/hello/web/site/about.

The config subdirectory includes environment configurations for your web and console applications as well as the future database settings. Edit /config/web.php to add urlManagement to the current web application. Add the following urlManager section within the components array:

Then, create an .htaccess file within /web where the primary index.php file exists:

Make sure mod_rewrite is running locally on MAMP; if not, check out this Stack Overflow guide.

In your browser, visit this URL: http://localhost/hello/web/site/about. You should see the Yii application About page and clicking on other menu options should bring up pretty URLs.


Views: 1124

Subscribe Us


Follow Us