Chủ Nhật, 22 tháng 9, 2013

Tạo một "Movie" có chức năng : thêm, xem, sửa, xóa dùng cakePHP (2.x) trên Linux

Posted by Unknown Chủ Nhật, tháng 9 22, 2013, under | No comments

1. create database :
We’re using MySQL, as it’s the most common of the free database engines available  for the movie application:

CREATE DATABASE linux_format_tutorial;
CREATE TABLE `movies` (
  `id` CHAR(36) NOT NULL PRIMARY KEY,
  `title` VARCHAR(255),
  `genre` VARCHAR(45),
  `rating` VARCHAR(45),
  `format` VARCHAR(45),
  `length` VARCHAR(45),
  `created` DATETIME,
  `modified` DATETIME
);

2. connectdatabase :
Open file "database.php " in path to "/var/www/cakephp/app/Config" (my project "cakephp" ) , and edit :

  var $default = array(
 ‘driver’ => ‘mysql’,
 ‘persistent’ => ‘false’,
 ‘host’ => ‘localhost’,// domain
 ‘port’ => ‘’,
 ‘login’ => ‘root’,// id login phpmyadmin
 ‘password’ => ‘huy’,//pasword login phpmyadmin
 ‘database’ => ‘linux_format_tutorial’,//name database
 ‘schema’ => ‘’,
 ‘prefix’ => ‘’,
 ‘encoding’ => ‘’
);


3. create file "MoviesController.php." in path to :" /var/www/cakephp/app/controller/", and "add" code :

<?php
class MoviesController extends AppController {
 public $helpers=array('Html','Form','Session');
 public $components=array('Session');
 
 public function index() {
  $movies = $this->Movie->find('all');
  $this->set('movies', $movies);
 }
 public function add() {
  if (!empty($this->data)) {
   $this->Movie->create($this->data);
   if ($this->Movie->save()) {
    $this->Session->setFlash(_('Thanh Cong'));
    $this->redirect(array('action' => 'index'));
    }
  }else {
   $this->Session->setFlash(_('Error'));
 
  }
 }

 public function delete($id = null) {
   if (!$id) {
    $this->Session->setFlash('Invalid id for movie');
    $this->redirect(array('action' => 'index'));
   }
   if ($this->Movie->delete($id)) {
    $this->Session->setFlash('Movie deleted');
   } else {
    $this->Session->setFlash(__('Movie was not deleted',
  true));
   }
   $this->redirect(array('action' => 'index'));
  }
 function edit($id = null) {
   if (!$id && empty($this->data)) {
    $this->Session->setFlash('Invalid movie');
    $this->redirect(array('action' => 'index'));
   }
   if (!empty($this->data)) {
    if ($this->Movie->save($this->data)) {
     $this->Session->setFlash('The movie has been saved');
     $this->redirect(array('action' => 'index'));
    } else {
     $this->Session->setFlash('The movie could not be saved. Please, try again.');
    }
   }
   if (empty($this->data)) {
    $this->data = $this->Movie->read(null, $id);
   }
  }
 function view($id = null) {
   if (!$id) {
    $this->Session->setFlash('Invalid movie');
    $this->redirect(array('action' => 'index'));
   }
   $this->set('movie', $this->Movie->findById($id));
  }
 
}

4. create file "SessionComponent.php" in path to : "/var/www/cakephp/app/Controller/Component/", and "add" code :

<?php
class SessionComponent extends Component {
public function setFlash($message) {
 
}
}

5. create folder "Movies" in path to : "/var/www/cakephp/app/View/" .

6. create file "index.ctp" in path to : "/var/www/cakephp/app/View/Movies ", and "add" code :

<div class="movies index" >
 <h2>Movies</h2>
 <table cellpadding="0" cellspacing="0">
  <tr>
   <th>Title</th>
   <th>Genre</th>
   <th>Rating</th>
   <th>Format</th>
   <th>Length</th>
   <th class="actions">Actions</th>
  </tr>
 <?php foreach ($movies as $movie): ?>
 <tr>
  <td><?php echo $movie['Movie']['title']; ?> </td>
  <td><?php echo $movie['Movie']['genre']; ?> </td>
  <td><?php echo $movie['Movie']['rating']; ?> </td>
  <td><?php echo $movie['Movie']['format']; ?> </td>
  <td><?php echo $movie['Movie']['length']; ?> </td>
  <td class="actions">
   <?php echo $this->Html->link('View',
array('action' => 'view', $movie['Movie']['id'])); ?>
   <?php echo $this->Html->link('Edit',
array('action' => 'edit', $movie['Movie']['id'])); ?>
   <?php echo $this->Html->link('Delete',
array('action' => 'delete', $movie['Movie']['id']),
null, sprintf('Are you sure you want to delete %s?', $movie['Movie']['title'])); ?>
  </td>
 </tr>
 <?php endforeach; ?>
 </table>
</div>
<div class="actions">
 <h3>Actions</h3>
 <ul>
  <li><?php echo $this->Html->link('New Movie', array('action' => 'add')); ?></li>
 </ul>
</div>

7. create file "add.ctp" in path to : " /var/www/cakephp/app/View/Movies/ ", and "add" code :

<div class="movies form">
<?php
echo $this->Form->create('Movie');
echo $this->Form->inputs(array('title', 'genre', 'rating', 'format', 'length'));
echo $this->Form->end('Add');
?>
</div>
<div class="actions">
 <h3>Actions</h3>
 <ul>
  <li><?php echo $this->Html->link('List Movies', array('action' => 'index'));?></li>
 </ul>
</div>

8.create file "view.ctp" in path to : " /var/www/cakephp/app/View/Movies/ ", and "add" code :
<div class="movies view">
 <h2> Movie </h2>
 <dl>
  <dt>Title</dt>
  <dd><?php echo $movie['Movie']['title']; ?></dd>
  <dt>Genre</dt>
  <dd><?php echo $movie['Movie']['genre']; ?></dd>
  <dt>Rating</dt>
  <dd><?php echo $movie['Movie']['rating']; ?></dd>
  <dt>Format</dt>
  <dd><?php echo $movie['Movie']['format']; ?></dd>
  <dt>Length</dt>
  <dd><?php echo $movie['Movie']['length']; ?></dd>
  <dt>Created</dt>
  <dd><?php echo $movie['Movie']['created']; ?></dd>
  <dt>Modified</dt>
  <dd><?php echo $movie['Movie']['modified']; ?></dd>
 </dl>
</div>
<div class="actions">
 <h3>Actions</h3>
 <ul>
  <li><?php echo $this->Html->link
('Edit Movie', array('action' => 'edit', $movie['Movie']['id'])); ?> </li>
  <li><?php echo $this->Html->link
('Delete Movie', array('action' => 'delete', $movie['Movie']['id']),
null, sprintf('Are you sure you want to delete # %s?', $movie['Movie']['id'])); ?> </li>
  <li><?php echo $this->Html->link
('List Movies', array('action' => 'index')); ?> </li>
  <li><?php echo $this->Html->link
('New Movie', array('action' => 'add')); ?> </li>
 </ul>
</div>
9. create file "edit.ctp" in path to : " /var/www/cakephp/app/View/Movies/ ", and "add" code :
<div class="movies form"><?phpecho $this->Form->create('Movie');echo $this->Form->inputs(array('id', 'title', 'genre', 'rating', 'format', 'length'));echo $this->Form->end('Edit');?></div><div class="actions"> <h3>Actions</h3> <ul>  <li><?php echo $this->Html->link('List Movies', array('action' => 'index'));?></li> </ul></div>

10. create file "delete.ctp" in path to : " /var/www/cakephp/app/View/Movies/ ", and "add" code :
<div class="movies form">
<?php
echo $this->Html->link('Delete', array('action' => 'delete', $movie['Movie']['id']), null,
sprintf('Are you sure you want to delete %s?', $movie['Movie']['title']) );
?>
11. Test : http://localhost/cakephp/movies/index(add,edit,delete,view )


12. Video demo :

Thứ Bảy, 21 tháng 9, 2013

How to install Cakephp On Linux Mint

Posted by Unknown Thứ Bảy, tháng 9 21, 2013, under | No comments

You have installed CakePHP 2.0 framwork using steps below:

1. Start the terminal
2. sudo mkdir /var/www/cakephp
3. sudo cp -r ~/cakephp/* /var/www/cakephp

( 2 and 3 you can :
  2. http://cakephp.org ->Download cakephp_version_RC.tar/...
  3. Extract Here -> rename ->cakephp ,copy and pass "cakephp" go to path /var/www/
)

4. cd /var/www ,and change tmp folder permisssion:
sudo chmod -R 777 cakephp/app/tmp
sudo chmod -R 777 cakephp/app/tmp/cache
sudo chmod -R 777 cakephp/app/tmp/cache/persistent
sudo chmod -R 777 cakephp/app/tmp/cache/models
sudo chmod -R 777 cakephp/app/tmp/logs

5. Enable mod-rewrite :
sudo a2enmod rewrite
Open file /etc/apache2/sites-enabled/000-default and change AllowOverride None to AllowOverride All

6. sudo vim /etc/apache2/sites-enabled/000-default
Restart Apache

7. sudo /etc/init.d/apache2 restart

8. Create database in phpmyadmin : data_name : cakephp

9. Change name file "database.php.default" in /var/www/cakephp/app/Config => "database.php"

10. Edit file "database.php" :

public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost', // host - doman website of you
'login' => 'root', // username login phpmyadmin
'password' => 'huy', // password login phpmyadmin
'database' => 'cakephp',// database
'prefix' => '',
//'encoding' => 'utf8',
);

11. Edit yourInstallation/app/config/core.php
search for Security.salt and change some random characters (this is so your application doesn't have the same security seed as a billion other installations, which would be a serious security loophole.
Do the same with Security.cipherSeed but use only numbers
save core.php
job done

12. Test: You opened your browser and typed address http://localhost/cakephp/


Thứ Sáu, 20 tháng 9, 2013

Kiểm tra tính hợp lệ của e-mail với PHP

Posted by Unknown Thứ Sáu, tháng 9 20, 2013, under | 1 comment

      Kiểm tra tính hợp lệ của các biểu mẫu là yếu tố rất quan trọng trong việc lập trình web. Trong bài này, tôi muốn giới thiệu đến các bạn cách dùng Regular Expression (RE) trong PHP để kiểm tra người dùng có nhập một địa chỉ e-mail hợp lệ hay không.
Trong PHP, tập hàm RE được chia làm 2 loại: 
- Hàm ereg: Cú pháp biểu thức chứa qui tắc chuẩn của PHP.
- Các hàm preg: Cú pháp biểu thức chứa qui tắc tương thích với perl.
Thực hành:
      Như các bạn đã biết, địa chỉ e-mail có dạng: username@domain.extension, ví dụ hameo87@gmail.com. Với một địa chỉ e-mail, thông thường có một phần mở rộng, ta sẽ viết:
eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9-] +\.[a-zA-Z.]{2,5}$', $email)
Tách ví dụ thành 3 phần nhỏ để dễ hiểu hơn:
- ^[a-zA-Z0-9._-]+@: Phần này có nhiệm vụ kiểm tra phần username của e-mail. Dấu mũ “^” ở đầu báo hiệu nơi bắt đầu chuỗi, nếu thiếu nó, người dùng có thể gõ bất kỳ thứ gì trước địa chỉ e-mail. Những ký tự trong dấu ngoặc vuông là những ký tự cho phép. Ta chấp nhận các chữ cái thường và hoa từ A đến Z, các chữ số từ 0 đến 9 và dấu chấm “.”, dấu gạch dưới “_”, dấu gạch trên “-”. Dấu cộng “+” ký tự “@”, sau ngoặc vuông đòi hỏi phải có một hoặc nhiều hơn một ký tự thuộc phạm vi cho phép trong dấu ngoặc vuông, vì vậy người dùng bắt buộc phải nhập phần username trong địa chỉ e-mail. Việc giới hạn số ký tự, ta sẽ xét ở phần sau. Cuối cùng, chữ @ cũng là chữ @ bình thường trong địa chỉ e-mail.
- [a-zA-Z0-9._-]+\.: Phần này cũng tương tự như kiểm tra username, và dấu cộng sau ngoặc buộc người dùng phải nhập tên miền của địa chỉ e-mail, ở cuối là một dấu “\” trước dấu “.” báo cho biểu thức rằng có một dấu chấm được yêu cầu tại vị trí này. Ý nghĩa của dấu “\” để thông báo đây là ký tự bình thường để tránh hiểu nhầm với ký tự “.” đứng một mình, sẽ được hiểu như một ký tự điều khiển cho biết tại vị trí đó có thể nhập ký tự bất kỳ.
- [a-zA-Z]{2,4}$: Phần này để kiểm tra phần mở rộng là phần cuối của biểu thức. Chúng ta chỉ cho phép các ký tự hoa, thường từ “A” đến “Z” thay vì dùng dấu cộng, ta dùng ngay {2,4} sau ngoặc vuông để qui định số ký tự tối thiểu và tối đa cho tên miền là 2 và 4 ( VD: vn, net, org ...). Cuối cùng kýá tự $ có nghĩa là kết thúc chuỗi, người dùng không thể nhập thêm gì phía sau tên miền.
     Như vậy là bạn đã biết cách kiểm tra biểu thức e-mail rồi nhé, với loại e-mail có tên miền cấp II (VD: abcd@pmail.vnn.vn ), bạn cũng làm tương tự.
Một số số ký hiệu khác trong cú pháp cơ bản:
?: Yêu cầu 0 hoặc 1 ký tự đứng trước.
*: Yêu cầu 0 hoặc nhiều ký tự đứng trước.
+: Yêu cầu 1 hoặc nhiều ký tự đứng trước.
{a}: Yêu cầu a kýá tự đứng trước.
{a,b}: Yêu cầu từ a đến b ký tự đứng trước.
{a,}: Yêu cầu lớn hơn hoặc bằng a ký tự đứng trước.
. : Bất kỳ ký tự nào. 
(a|b): a hoặc b. 
\s: Xóa sạch khoảng trắng.

1. VD1: 

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Học PHP - Regular Expression: Viết biểu thức Reg kiểm tra Địa chỉ email hợp lệ</title>
</head>
<body>
<?php
if($_POST){
$string = $_POST['email'];
$pattern = '#^[a-z][a-z0-9\._]{2,31}@[a-z0-9\-]{3,}(\.[a-z]{2,4}){1,2}$#';
if(preg_match($pattern, $string, $match) == 1){
$report = '<span style=\'color:#298426\'>Bạn vừa nhập vào một địa chỉ Email hợp lệ!</span>';
}
else{
$report = '<span style=\'color:#FF0400\'>Bạn vừa nhập vào một địa chỉ Email không hợp lệ!</span>';
}
}






Thứ Năm, 19 tháng 9, 2013

Hướng dẫn phân chia trang web bằng PHP và Ajax

Posted by Unknown Thứ Năm, tháng 9 19, 2013, under | No comments

Cạch , làm biến diễn dãi quá, trong code mình chú thích rồi nha !
Các bước thực hiện:

1. Tạo database trong phpmyadmin với tên "chiarang" ( có thể khác, tùy bạn, nếu khác bạn nên thay đôi dataname trong file "connec.php" để có thể kết nối đến database trên server ).

2. Trong database " chiatrang ", tạo một table với tên "paging", có nội dung như sau:

create table paging (
id int(10) not null  AUTO_INCREMENT,
msg varchar(500) not null,
PRIMARY KEY (id)
);

3. Trong thư mục webroot tạo thư mục "chiatrang" .

4. Trong thư mục "chiatrang" vừa tạo, tạo các file : index.php, insert_data.php, load_data.php, connec.php, paging_ajax.php ; tạo thư mục js chứa 2 file : layout.css , paging.js ; tạo thư mục images chứa 2 file ảnh . Cấu trúc thư mục như sau :

-chiatrang
------------index.php
------------insert_data.php
------------load_data.php
------------connec.php
------------paging_ajax.php
------------js
-----------------------------layout.css
-----------------------------paging.js

------------images
----------------------------- 2 file ảnh



a . File "index.php" có nội dung như sau :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>Phân trang PHP bằng Ajax jQuery hoàn chỉnh</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="js/layout.css" media="screen" rel="stylesheet" type="text/css" >
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript" src="js/paging.js"></script>
   
    </head>
<body>
<div align="center" ><h1>Phần nội dung hiển thị trên trang </h1></div>
    <div id="loading"></div>
    <div id="container" style="margin-bottom:100px">
        <div class="data"></div>
      <div class="pagination"></div>
     </div>
<div align="center" ><h1> Phần nhập nội dung cho trang </h1></div>
<form action="" method="post">
<textarea rows="15" cols="60" type="text"  required="required" name="chenvao"></textarea>
<input type="submit" name="ok" value="Submit" >
</form>
</body>
</html>

<?php
include "insert_data.php";
?>

b. File "insert_data.php" có nội dung như sau :

<?php
$chen="";
include "connec.php";
if ( isset($_POST['ok']) ){
if(isset($_POST['chenvao'])!= NULL) {
$chen = addslashes( $_POST['chenvao'] );
$sql_query = @mysql_query("SELECT msg FROM paging WHERE msg='{$chen}'");
// Nếu msg này không tồn tại thì insert data
if ( @mysql_num_rows( $sql_query ) <= 0 ){
mysql_query("INSERT INTO paging (msg) VALUES ('{$chen}')");
}
else {
require_once "index.php";
}
}
else {
require_once "index.php";
}
}
?>

c. File "load_data.php" có nội dung như sau:

<?php
// KIỂM TRA TỒN TẠI PAGE HAY KHÔNG
if(isset($_POST["page"]))
{
// ĐƯA 2 FILE VÀO TRANG & KHỞI TẠO CLASS
include "connec.php";
require_once "paging_ajax.php";
$paging = new paging_ajax();

// ĐẶT CLASS CHO THÀNH PHẦN PHÂN TRANG THEO Ý MUỐN
$paging->class_pagination = "pagination";
$paging->class_active = "active";
$paging->class_inactive = "inactive";
$paging->class_go_button = "go_button";
$paging->class_text_total = "total";
$paging->class_txt_goto = "txt_go_button";

// SỐ PHẦN TỬ TRÊN 1 TRANG , CÓ NGHĨA LÀ SỐ DÒNG TRONG BẢNG CSDL
    $paging->per_page = 5;
 
    // LẤY GIÁ TRỊ PAGE THÔNG QUA PHƯƠNG THỨC POST
    $paging->page = $_POST["page"];
 
    // VIẾT CÂU TRUY VẤN & LẤY KẾT QUẢ TRẢ VỀ
    $paging->text_sql = "SELECT id,msg FROM paging";
    $result_pag_data = $paging->GetResult();

    // BIẾN CHỨA KẾT QUẢ TRẢ VỀ
$message = "";

// DUYỆT MẢNG LẤY KẾT QUẢ

while ($row = mysql_fetch_array($result_pag_data)) {
$message .= "<li><strong>" . $row['id'] . "</strong> ".">.   ". $row['msg'] . "</li>";
echo "</br>";
}

// ĐƯA KẾT QUẢ VÀO PHƯƠNG THỨC LOAD() TRONG LỚP PAGING_AJAX
$paging->data = "<div class='data'><ul>" . $message . "</ul></div>"; // Content for Data  
echo $paging->Load();  // KẾT QUẢ TRẢ VỀ

}


d. File "connec.php" có nội dung như sau :

<?php
$mysql_hostname = "localhost";   // host MySQL
$mysql_user = "root"; // username MySQL
$mysql_password = "huy"; // password MySQL
$mysql_database = "chiatrang"; // database name

// KẾT NỐI & CHỌN DATABASE
$db = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("CAN NOT CONNECT DATABASE");
mysql_select_db($mysql_database, $db) or die("CAN NOT SELECT DATABASE");

// THIẾT LẬP UTF8 CHO DB
mysql_query("SET NAMES 'utf8'", $db);
/* mysql_set_charset('utf8',$db); */

?>

e. File "paging_ajax.php" có nội dung như sau:

<?php
class paging_ajax
{
    public $data; // DATA
    public $per_page = 5; // SỐ RECORD TRÊN 1 TRANG
    public $page; // SỐ PAGE
    public $text_sql; // CÂU TRUY VẤN
 
    // THÔNG SỐ SHOW HAY HIDE
    public $show_pagination = true;
    public $show_goto = false;
    public $show_total = true;
 
    // TÊN CÁC CLASS
    public $class_pagination;
    public $class_active;
    public $class_inactive;
    public $class_go_button;
    public $class_text_total;
    public $class_txt_goto;  
 
    private $cur_page; // PAGE HIỆN TẠI
    private $num_row; // SỐ RECORD
 
    // PHƯƠNG THỨC LẤY KẾT QUẢ CỦA TRANG
    public function GetResult()
    {
        global $db; // BIỀN $db TOÀN CỤC
     
        // TÌNH TOÁN THÔNG SỐ LẤY KẾT QUẢ
        $this->cur_page = $this->page;
        $this->page -= 1;
        $this->per_page = $this->per_page;
        $start = $this->page * $this->per_page;
     
        // TÍNH TỔNG RECORD TRONG BẢNG
$result = mysql_query($this->text_sql);
        $this->num_row = mysql_num_rows($result);
     
        // LẤY KẾT QUẢ TRANG HIỆN TẠI
        return mysql_query($this->text_sql." LIMIT $start, $this->per_page");
    }
 
    // PHƯƠNG THỨC XỬ LÝ KẾT QUẢ VÀ HIỂN THỊ PHÂN TRANG
    public function Load()
    {
        // KHÔNG PHÂN TRANG THÌ TRẢ KẾT QUẢ VỀ
        if(!$this->show_pagination)
            return $this->data;
     
        // SHOW CÁC NÚT NEXT, PREVIOUS, FIRST & LAST
        $previous_btn = true;
        $next_btn = true;
        $first_btn = true;
        $last_btn = true;  
     
        // GÁN DATA CHO CHUỖI KẾT QUẢ TRẢ VỀ
        $msg = $this->data;
     
        // TÍNH SỐ TRANG
        $count = $this->num_row;
        $no_of_paginations = ceil($count / $this->per_page);
     
        // TÍNH TOÁN GIÁ TRỊ BẮT ĐẦU & KẾT THÚC VÒNG LẶP
        if ($this->cur_page >= 7) {
            $start_loop = $this->cur_page - 3;
            if ($no_of_paginations > $this->cur_page + 3)
                $end_loop = $this->cur_page + 3;
            else if ($this->cur_page <= $no_of_paginations && $this->cur_page > $no_of_paginations - 6) {
                $start_loop = $no_of_paginations - 6;
                $end_loop = $no_of_paginations;
            } else {
                $end_loop = $no_of_paginations;
            }
        } else {
            $start_loop = 1;
            if ($no_of_paginations > 7)
                $end_loop = 7;
            else
                $end_loop = $no_of_paginations;
        }
     
        // NỐI THÊM VÀO CHUỖI KẾT QUẢ & HIỂN THỊ NÚT FIRST
        $msg .= "<div class='$this->class_pagination'><ul>";
        if ($first_btn && $this->cur_page > 1) {
            $msg .= "<li p='1' class='active'>Đầu</li>";
        } else if ($first_btn) {
            $msg .= "<li p='1' class='$this->class_inactive'>Đầu</li>";
        }
 
        // HIỂN THỊ NÚT PREVIOUS
        if ($previous_btn && $this->cur_page > 1) {
            $pre = $this->cur_page - 1;
            $msg .= "<li p='$pre' class='active'>Trước</li>";
        } else if ($previous_btn) {
            $msg .= "<li class='$this->class_inactive'>Cuối</li>";
        }
        for ($i = $start_loop; $i <= $end_loop; $i++) {
     
            if ($this->cur_page == $i)
                $msg .= "<li p='$i' class='actived'>{$i}</li>";
            else
                $msg .= "<li p='$i' class='active'>{$i}</li>";
        }
     
        // HIỂN THỊ NÚT NEXT
        if ($next_btn && $this->cur_page < $no_of_paginations) {
            $nex = $this->cur_page + 1;
            $msg .= "<li p='$nex' class='active'>Sau</li>";
        } else if ($next_btn) {
            $msg .= "<li class='$this->class_inactive'>Sau</li>";
        }
     
        // HIỂN THỊ NÚT LAST
        if ($last_btn && $this->cur_page < $no_of_paginations) {
            $msg .= "<li p='$no_of_paginations' class='$this->class_active'>Cuối</li>";
        } else if ($last_btn) {
            $msg .= "<li p='$no_of_paginations' class='$this->class_inactive'>Cuối</li>";
        }
     
        // SHOW TEXTBOX ĐỂ NHẬP PAGE KO ?
        if($this->show_goto)
            $goto = "<input type='text' id='goto' class='$this->class_txt_goto' size='1' style='margin-top:-1px;margin-left:40px;margin-right:10px'/><input type='button' id='go_btn' class='$this->class_go_button' value='Đến'/>";
        if($this->show_total)
            $total_string = "<span id='total' class='$this->class_text_total' a='$no_of_paginations'>Trang <b>" . $this->cur_page . "</b>/<b>$no_of_paginations</b></span>";
        $stradd =  $goto . $total_string;
     
        // TRẢ KẾT QUẢ TRỞ VỀ
        return $msg . "</ul>" . $stradd . "</div>";  // Content for pagination
    }  
         
}

?>

f. File "layout.css" có nội dung như sau :

@CHARSET "ISO-8859-1";
/*============== STYLE FOR PAGE ==============*/
*{margin:0px; padding:0px;}
body{
    width: 500px; background: #000;
    margin: 0 auto; padding: 0;
}
h1{color:#DB2E66; margin:20px 0px;}
#loading{ width: 300px;  position: absolute; top: 80px; right:160px;}

/*============== STYLE FOR PAGING ==============*/
#container .pagination ul li.active,
#container .pagination ul li.inactive:hover{
background-color: #DB2E66; color:#fff;
    border:1px solid #DB2E66; cursor: default;
}
#container .pagination ul li.inactive{
background-color: #000; color: #DB2E66;
border: 1px solid #eaeaea; cursor: default;
}
#container .pagination ul li.actived{color:#DB2E66;background-color:#fff; border:1px solid #fff;}
#container .data ul li{
    list-style: none;
    margin: 5px 0; color: #fff;
    font:normal 13px verdana;
}

#container .pagination{  width: 550px;   height: 25px; margin-top:20px;}
#container .pagination ul li{
    list-style: none;
    float: left; margin: 0 3px;
    border: 1px solid #eaeaea;
    padding: 2px 6px 2px 6px;
    font: bold 14px arial;
    background-color: #000; color: #DB2E66;
}
#container .pagination ul li:hover{
    background-color: #DB2E66;
  border: 1px solid #DB2E66;
    cursor: pointer; color: #fff;
}
.go_button{
background-color:#DB2E66;
border:1px solid #fff;
color:#cc0000;padding:2px 6px;
cursor:pointer;position:absolute;margin-top:-1px;
}
.total{ float:right;font-family:arial;color:#999; }

g. File "paging.js" có nội dung như sau :

 $(document).ready(function(){

    // PHƯƠNG THỨC SHOW HÌNH LOADING
    function loading_show(){
        $('#loading').html("<img src='images/image-loading-animation.gif'/>").fadeIn('fast');
    }

    // PHƯƠNG THỨC ẨN HÌNH LOADING
    function loading_hide(){
        $('#loading').fadeOut('fast');
    }             

    // PHƯƠNG THỨC LOAD KẾT QUẢ 
    function loadData(page){
        loading_show();                    
        $.ajax
        ({
            type: "POST",
            url: "load_data.php",
            data: "page="+page,
            success: function(msg)
            {
                $("#container").ajaxComplete(function(event, request, settings)
                {
                    loading_hide();
                    $("#container").html(msg);
                });
            }
        });
    }

    // LOAD GIÁ TRỊ MẶC ĐỊNH PAGE = 1 CHO LẦN ĐẦU TIÊN
    loadData(1);  

    // LOAD KẾT QUẢ CHO TRANG
    $('#container .pagination li.active').live('click',function(){
        var page = $(this).attr('p');
        loadData(page);
    });           

    // PHƯƠNG THỨC DÙNG ĐỂ HIỆN KẾT QUẢ KHI NHẬP GIÁ TRỊ PAGE VÀO TEXTBOX
    // BẠN CÓ THỂ MỞ TEXTBOX LÊN TRONG CLASS PHÂN TRANG
    $('#go_btn').live('click',function(){
        var page = parseInt($('#goto').val());
        var no_of_pages = parseInt($('.total').attr('a'));
        if(page != 0 && page <= no_of_pages){
            loadData(page);
        }else{
            alert('HÃY NHẬP GIÁ TRỊ TỪ 1 ĐẾN '+no_of_pages);
            $('.goto').val("").focus();
            return false;
        }
    });
});

h. Hai file ảnh :





5. Video demo :

6. Link tải file :

Thứ Ba, 10 tháng 9, 2013

Xây dựng tính năng thêm, sửa, xóa của một album nhạc bằng Zend Framework trên Linux

Posted by Unknown Thứ Ba, tháng 9 10, 2013, under | No comments


Mình viết bài thì rất hạn chế ly thuyết, điễn dải nhiều ,vì mình nghèo văn ,các bạn thông cảm nha !


Các bước thực hiện:

1. Tạo database trong mysql : z-click ( terminal : create database z-click; )

2. Tạo 1 table trong database z-click : albums
CREATE TABLE albums (
id int(11) NOT NULL auto_increment,
artist varchar(100) NOT NULL,
title varchar(100) NOT NULL,
PRIMARY KEY (id)
);

3. Chèn vào table  albums nội dung sau :

INSERT INTO albums (artist, title)
VALUES
('Paolo Nutine', 'Sunny Side Up'),
('Florence + The Machine', 'Lungs'),
('Massive Attack', 'Heligoland'),
('Andre Rieu', 'Forever Vienna'),
('Sade', 'Soldier of Love');

3. Trong terminal ,di chuyển con trỏ đến thư mục cài đặt ZendFramework , nhập vào lần lược các dòng lệnh sau:

zf create action add Index
zf create action edit Index
zf create action delete Index

4. Trong terminal ,di chuyển con trỏ đến thư mục cài đặt ZendFramework , nhập vào  dòng lệnh sau:

zf create db-table Albums albums

5. từ đường dẫn  .. /application/models/DbTable/Albums.php ,mở file Albums.php lên , cho đoạn code sau vào ,rồi save lại


<?php
class Application_Model_DbTable_Albums extends Zend_Db_Table_Abstract
{
protected $_name = 'albums';
public function getAlbum($id)
 {
$id = (int)$id;
$row = $this->fetchRow('id = ' . $id);
if (!$row) {
throw new Exception("Could not find row $id");
 }
return $row->toArray();
 }
public function addAlbum($artist, $title)
 {
$data = array(
'artist' => $artist,
'title' => $title,
 );
$this->insert($data);
 }
public function updateAlbum($id, $artist, $title)
 {
$data = array(
'artist' => $artist,
'title' => $title,
 );
$this->update($data, 'id = '. (int)$id);
 }
public function deleteAlbum($id)
 {
$this->delete('id =' . (int)$id);
 }
}

6. Trong terminal ,di chuyển con trỏ đến thư mục cài đặt ZendFramework , nhập vào  dòng lệnh sau:

zf enable layout

7. từ đường dẫn  .. /application/layouts/scripts/layout.phtml  ,mở file layout.phtml lên , cho đoạn code sau vào ,rồi save lại :

<?php
$this->headMeta()->appendHttpEquiv('Content-Type', 'text/html;charset=utf-8');
$this->headTitle()->setSeparator(' - ');
$this->headTitle('Zend Framework Tutorial');
echo $this->doctype(); ?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<?php echo $this->headMeta(); ?>
<?php echo $this->headTitle(); ?>
<?php echo $this->headMeta(); ?>
<?php echo $this->headTitle(); ?>
<?php echo $this->headLink()->prependStylesheet($this->baseUrl().'/css/site.css'); ?>
</head>
<body>
<div id="content">
<h1><?php echo $this->escape($this->title); ?></h1>
<?php echo $this->layout()->content; ?>
</div>
</body>
</html>

8.  Tạo file site.css  theo đường daazn sau : .. /public/css/site.css ( tạo folder css nữa  nha ) ,sau đó lại cho code sau vào , save lại :

body,html {
margin: 0 50px;
font-family: Verdana,sans-serif;
}
h1 {
font-size: 1.4em;
color: #008000;
}
a {
color: #008000;
}
/* Table */
th {
text-align: left;
}
td, th {
padding-right: 5px;
}
/* style form */
form dt {
width: 100px;
display: block;
float: left;
clear: left;
}
form dd {
margin-left: 0;
float: left;
}
form #submitbutton {
margin-left: 100px;
}

9.   từ đường dẫn     .. /application/views/scripts/index/index.phtml ,mở file index.phtml lên , cho đoạn code sau vào ,rồi save lại :

<?php
$this->title = "My Albums";
$this->headTitle($this->title);
?>
<p><a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'add'));?>">Add new album</a></p>
<table>
<tr>
<th>Title</th>
<th>Artist</th>
<th>&nbsp;</th>
</tr>
<?php foreach($this->albums as $album) : ?>
<tr>
<td><?php echo $this->escape($album->title);?></td>
<td><?php echo $this->escape($album->artist);?></td>
<td>
<a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'edit', 'id'=>$album->id));?>">Edit</a>
<a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'delete', 'id'=>$album->id));?>">Delete</a>
</td>
</tr>
<?php endforeach; ?>
</table>


10.  từ đường dẫn     .. /application/forms/Album.php ,mở file Album.php lên , cho đoạn code sau vào ,rồi save lại :


<?php
class Application_Form_Album extends Zend_Form
{
public function init()
{
$this->setName('album');
$id = new Zend_Form_Element_Hidden('id');
 $id->addFilter('Int');
$artist = new Zend_Form_Element_Text('artist');
$artist->setLabel('Artist')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$title = new Zend_Form_Element_Text('title');
$title->setLabel('Title')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$submit = new Zend_Form_Element_Submit('submit');
$submit->setAttrib('id', 'submitbutton');
$this->addElements(array($id, $artist, $title, $submit));
}
}

11.   từ đường dẫn     .. /application/views/scripts/index/add.phtml, mở file add.phtml lên , cho đoạn code sau vào ,rồi save lại :

<?php
$this->title = "Add new album";
$this->headTitle($this->title);
echo $this->form ;
?>

12.    từ đường dẫn     ..  /application/views/scripts/index/edit.phtml, mở file edit.phtml lên , cho đoạn code sau vào ,rồi save lại :

<?php
$this->title = "Edit album";
$this->headTitle($this->title);
echo $this->form ;
?>

13.   từ đường dẫn     ..  /application/views/scripts/index/delete.phtml  , mở file delete.phtml lên , cho đoạn code sau vào ,rồi save lại :

<?php
$this->title = "Delete album";
$this->headTitle($this->title);
?>
<p>Are you sure that you want to delete
 '<?php echo $this->escape($this->album['title']); ?>' by
 '<?php echo $this->escape($this->album['artist']); ?>'?
</p>
<form action="<?php echo $this->url(array('action'=>'delete')); ?>" method="post">
<div>
<input type="hidden" name="id" value="<?php echo $this->album['id']; ?>" />
<input type="submit" name="del" value="Yes" />
<input type="submit" name="del" value="No" />
</div>
</form>

14. từ đường dẫn     .. /application/controllers/IndexController.php  , mở file IndexController.php lên , cho đoạn code sau vào ,rồi save lại :

<?php

class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
$albums = new Application_Model_DbTable_Albums();
$this->view->albums = $albums->fetchAll();
    }

    public function aboutAction()
    {
        // action body
    }

    public function vcdAction()
    {
        // action body
    }

    public function showsAction()
    {
        // action body
    }

    public function contactAction()
    {
        // action body
    }

    public function newsAction()
    {
        // action body
    }

    public function addAction()
    {
        // action body

$form = new Application_Form_Album();
$form->submit->setLabel('Add');
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$artist = $form->getValue('artist');
$title = $form->getValue('title');
$albums = new Application_Model_DbTable_Albums();
$albums->addAlbum($artist, $title);
$this->_helper->redirector('index');
} else {
$form->populate($formData);
}
}

    }

    public function editAction()
    {
$form = new Application_Form_Album();
$form->submit->setLabel('Save');
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$id = (int)$form->getValue('id');
$artist = $form->getValue('artist');
$title = $form->getValue('title');
$albums = new Application_Model_DbTable_Albums();
$albums->updateAlbum($id, $artist, $title);
$this->_helper->redirector('index');
} else {
$form->populate($formData);
}
} else {
$id = $this->_getParam('id', 0);
if ($id > 0) {
$albums = new Application_Model_DbTable_Albums();
$form->populate($albums->getAlbum($id));
}
}

    }

    public function deleteAction()
    {
if ($this->getRequest()->isPost()) {
$del = $this->getRequest()->getPost('del');
if ($del == 'Yes') {
$id = $this->getRequest()->getPost('id');
$albums = new Application_Model_DbTable_Albums();
$albums->deleteAlbum($id);
}
$this->_helper->redirector('index');
} else {
$id = $this->_getParam('id', 0);
$albums = new Application_Model_DbTable_Albums();
$this->view->album = $albums->getAlbum($id);
}
    }


}


14.  Sửa lại file application như sau :

[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
resources.view[] =
resources.view.doctype = "XHTML1_STRICT"

// phan nay dung ket noi csdl, ban nen thay doi cho phu hop nha

resources.db.adapter = "Pdo_Mysql"
resources.db.params.charset = "utf8"
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = "huy"
resources.db.params.dbname = "z_click"

//

[staging : production]

[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1

[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1

15. Sửa lại file Bootstap.php như sau :
<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

protected function _initDoctype()
{
      $this->bootstrap('view');
      $view = $this->getResource('view');
$view->doctype('XHTML1_STRICT');

}
}

16. Tài lệu : https://docs.google.com/file/d/0B6JhErFMAx7saE5raFBycWdodzQ/edit

17. Video demo : http://www.youtube.com/watch?v=tV1Pw-cJ6VM&feature=youtu.be



Thứ Hai, 9 tháng 9, 2013

Thao tác với Form trong Zend Framework trên Linux

Posted by Unknown Thứ Hai, tháng 9 09, 2013, under | No comments

Mình cài Zend Framework trong thư mục : /var/www/ (tức là : /var/www/Zend )
Các bước thực hiện :

1. Tạo file  UserController.php , file này đặt theo đường dẫn sau nha : /var/www/Zend/application/controller , nội dung file như sau :

<?php
class UserController extends Zend_Controller_Action{
public function indexAction(){
        $form=new Form_User;
if($this->_request->isPost()){
$name=$this->_request->getPost('name');
echo "Ten cua ban la :";
echo  $name;
echo "</br>";
echo "Email cua ban la :";
$email=$this->_request->getPost('email');
echo $email;
echo "</br>";
echo "Gioi tinh cua ban la :";
$gender=$this->_request->getPost('gender');
echo $gender;
echo "</br>";
echo "Quoc gia cua ban la :";
$country=$this->_request->getPost('country');
echo $country;
echo "</br>";
   echo " cm  gia cua ban la :";
$note=$this->_request->getPost('note');
echo $note;
echo "</br>";

}
$this->view->form=$form;
    }

}

2. Tạo file User.php , file này đặt trong thư mục : /var/www/Zend/application/forms , nội dung file như sau :

<?php
class Form_User extends Zend_Form{

    public function init()
    {
        $this->setAction('')->setMethod('post');
$name=$this->createElement("text","name",array(
//"label" => "Full Name",
"size" => "30",
));
$email=$this->createElement("text","email",array(
//"label" => "Email",
"size" => "30",
));
$gender=$this->createElement("radio","gender",array(
//"label" => "Gender",
 "multioptions"=> array(
  "1" => "Male",
"2" => "Female",
 ),
));
$country=$this->createElement("select","country",array(
//"label" => "Country",
 "multioptions"=> array(
  "1" => "VietNam",
"2" => "Cambodia",
"3" => "Thai Lan",
 )
));
$note=$this->createElement("textarea","note",array(
//"label" => "Note",
"cols" => "30",
"rows"  => "5",
));
$submit=$this->createElement("submit","submit");
$this->setDecorators(array(
array('viewScript',
array('viewScript'=>'Form_Register.phtml'),
)));
$name->removeDecorator('HtmlTag')
->removeDecorator('Label');
$email->removeDecorator('HtmlTag')
->removeDecorator('Label');
$gender->removeDecorator('HtmlTag')
->removeDecorator('Label');
$country->removeDecorator('HtmlTag')
->removeDecorator('Label');
$note->removeDecorator('HtmlTag')
->removeDecorator('Label');
$submit->removeDecorator('DtDdWrapper');

$this->addElements(array($name,$email,$gender,$country,$note,$submit));
    }
}

3. Tạo file Form_Register.phtml , file này đặt trong /var/www/Zend/application/views/scripts , nội dung file như sau :

<form action='<?php echo $this->element->getAction(); ?>'
method= '<?php echo $this->element->getMethod(); ?>'>
<p>Your Name:<br />
<?php echo $this->element->name; ?>
</p>
<p>Your Email:<br />
<?php echo $this->element->email; ?>
</p>
<p>Your Gender:<br />
<?php echo $this->element->gender; ?>
</p>
<p>Your Country:<br />
<?php echo $this->element->country; ?>
</p>
<p>Your Note:<br />
<?php echo $this->element->note; ?>
</p>
<p><?php echo $this->element->submit; ?>
</p>
</form>

4. Tìm file Bootstap.php trong thư mục : /var/www/Zend/application , thêm nội dung sau vào :

protected function _initAutoload(){ 
        $autoloader = new Zend_Application_Module_Autoloader(array( 
                    'namespace' => '', 
                    'basePath' => dirname(__FILE__),));

        return $autoloader; 
    }


5. Tạo file index.phtml ,file này nàm trong thư mục :/var/www/Zend/application/views/scripts/user , nội dung file :

<?php
echo $this->form;
?>


6. Demo : bạn mở trình duyệt lên và gõ vào: localhost/thư mục cài Zend Framework /user ,rồi enter xem kết quả .

7. Video demo :









Hiệu chỉnh layout Zend Framework trên Linux

Posted by Unknown Thứ Hai, tháng 9 09, 2013, under | No comments

Hướng dẫn chạy ứng dụng đầu tiên cho Zend Framework trên Linux

Posted by Unknown Thứ Hai, tháng 9 09, 2013, under | No comments

Hướng dẫn cài Zend Framework trên Linux Mint 15

Posted by Unknown Thứ Hai, tháng 9 09, 2013, under | No comments


HOW TO INSTALL ZEND FRAMEWORK IN LINUX MINT
you have installed:
-install websever
-install php
-install phpmysqladmin

1. install ZF:
sudo apt-get install zend-framework

2. Check version ZF:
zf show version

3. Move the cursor to folther webroot:
cd /var/www

4. Creating profect for ZF( my profect "Zend"):
zf create project Zend

5.  Move the cursor to folther "library" in profect :
cd /library

6. Copy library for zend :
sudo ln -s /usr/share/php/libzend-framework-php/Zend/

7. See tree Folther ZF:
tree 
(install tree: sudo apt-get install tree )

8. Change https://localhost/Zend -> http://Zend/

a. find host in folther " /etc ":
Del " 127.0.0.1  localhost"
add " 127.0.0.1  Server "

b. find default in folther "/etc/apache2/sites-available":
add code :

NameVirtualHost *:80
<VirtualHost *:80>
ServerName Server
DocumentRoot /var/www/Zend/public/>
<Directory /var/www/Zend/public>
                Options Indexes FollowSymLinks MultiViews
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>

9. test : https://sever/       or  https://localhost/Zend/public/

10. Note :
a. restart apache2 : service apache2 restart
b. admin for folder/file : sudo -i -> password ->enter->cd /path/to/folder -> chown user.user folder/file

10. The end. ( visit :https://toantinit.blogspot.com )

Thứ Hai, 2 tháng 9, 2013

Hướng dẫn 3 cách cài chương trình cho Linux ( phổ cập Unix :: )

Posted by Unknown Thứ Hai, tháng 9 02, 2013, under | No comments

Cách tích hợp Unikey nhiều kiểu gõ cho Unikey

Posted by Unknown Thứ Hai, tháng 9 02, 2013, under | No comments

Khi một máy tính được sử dùng cho nhiều người, mỗi người lại thạo 1 kiểu gõ, để không phải chuyển đổi giữa các kiểu gõ, ta tổng hợp nhiều kiểu gõ thành một kiểu tổ hợp.
Video demo tổng hợp 2 kiểu gõ Telex, VNI thành một kiểu .
Link:http://www.youtube.com/watch?v=XJ9MeuAQpvg&feature=youtu.be


Xem Nhiều

Bài đăng phổ biến

Lưu trữ blog

Blog Archive