Thứ Bảy, 8 tháng 6, 2019

Tăng tốc MySQL


MySQL là 1 Database kết hợp chặt chẽ với PHP trong rất nhiều ứng dụng web động. Nhờ tính năng mã nguồn mở và nhỏ gọn , MySQL hiện đang là hệ Database nhanh nhất cho các ứng dụng thông thường. Tuy nhiên theo thời gian , các ứng dụng web sử dụng MySQL ngày càng "phình" to ra và Website của bạn ngày càng chạy chậm đi. Đó có phải là điều không thể tránh khỏi ? Hãy tham khảo bài viết sau đây để tăng tốc MySQL và website của bạn lên gấp nhiều lần.
Một ngày kia bạn nhận ra rằng website của bạn chạy chậm đi, có thể là do đường truyền nhưng còn 1 nguyên nhân khác, đó là máy chủ server tính toán quá nhiều dẫn đến kết quả đưa ra chậm (Xem phần phụ lục để biết cách xác định nguyên nhân gây chậm). Đây là điều thường thấy ở những website về Diễn Đàn (Forum) , Tin Tức (Portal) và Thương mại điện tử (Ecommerce). Khi số lượng thành viên , số lượng bài viết tăng lên , đồng nghĩa với việc Database khi truy vấn (query) 1 yêu cầu phải duyệt qua tất cả các dữ liệu hiện có để tìm ra dữ liệu thích hợp. Cũng giống như 1 quyển sách. Nếu sách là mỏng , bạn dễ dàng tìm ra thông tin mình cần. Nhưng khi sách dầy lên , thời gian tìm kiếm của bạn sẽ tăng đáng kể.

Việc Database quá tải còn dẫn đến nhiều thiệt hại khác, các hàng đợi(Queuie) dài ra , file logs lớn lên chiếm hết không gian đĩa và user khi kết nối sẽ bị từ chối. Rõ ràng là câu báo lỗi "Too many connections" không phải là hiếm gặp trong các website trên Internet. Những lỗi trên thông thường bắt nguồn từ khâu định nghĩa Database (define) hay không sử dụng "Mục Lục" (Indexes). Khắc phục những thiếu sót trên , Database của bạn sẽ "nhẹ nhàng" và nhanh chóng đáng kể. Hãy xem xét ví dụ sau:


CODE

CREATE TABLE employee (
employee_number char(10) NOT NULL,
firstname varchar(40),
surname varchar(40),
address text,
tel_no varchar(25),
salary int(11),
overtime_rate int(10) NOT NULL
);



Và để tìm thông tin Lương của Nguyễn Nam (mã số 101802) , bạn sẽ query như sau:

CODE

SELECT salary FROM employee WHERE employee_number = '101832';


MySQL biết rằng phải tìm ở table Employee nhưng nó sẽ không biết bắt đầu từ đâu. Thậm chí nó cũng không biết trước rằng có bao nhiêu kết quả . Do đó nó sẽ duyệt qua tất cả danh sách (vd Hơn 300000 người) để tìm thông tin về Nguyễn Nam.

"Mục Lục" (Index) là 1 file riêng biệt được lưu trữ ở máy chủ và chỉ chứa những Fields mà bạn muốn nó chứa. Nếu bạn tạo 1 Index cho Field employee_number char (mã số công nhân) , MySQL sẽ dễ dàng tìm ra được mã số 1 cách nhanh chóng. Trở lại ví dụ quyển sách , khi cần tìm 1 thông tin , ta thường lật ngay tới phần "Mục Lục" và tìm từ đó để tăng tốc độ tìm. Và việc tạo ra Index này sẽ làm bạn thấy Database của bạn chạy nhanh 1 cách khác thường.

Nhưng trước khi sửa lại cấu trúc của table ở trên , tôi sẽ hướng dẫn bạn 1 chút về cách theo dõi kết quả "Tăng tốc MySQL" mà bạn đang làm. Hãy sử dụng lệnh EXPLAIN

Cú pháp:
CODE

EXPLAIN Query;


Bằng lệnh này bạn sẽ nhận ra được với câu Query của bạn , điều gì đang xảy ra và kiểu kết hợp (Join) nào đang diễn ra bên trong.

Xem ví dụ sau:

CODE

MySQL>EXPLAIN SELECT employee_number,firstname,surname FROM employee WHERE employee_number= '10875';
+----------+------+---------------+------+---------+------+------+------------+
| table | type | possible_keys | key | key_len | ref | rows | Extra |
+----------+------+---------------+------+---------+------+------+------------+
| employee | ALL | NULL | NULL | NULL | NULL | 9475 | where used |
+----------+------+---------------+------+---------+------+------+------------+


Giải thích:

- table : Table nào đang liên quan đến output data
- type : Đây là thông tin quan trọng , nó cho chúng ta biết kiểu query nào nó đang sử dụng. Mức độ từ tốt nhất đến chậm nhất như sau: system, const, eq_ref, ref, range, index, all
- possible_keys : Đưa ra những Index có thể sử dụng để query
- key : và Index nào đang được sử dụng
- key_len : Chiều dài của từng mục trong Index
- ref : Cột nào đang sử dụng
- rows : Số hàng (rows) mà MySQL dự đoán phải tìm
- extra : Thông tin phụ , thật tệ nếu tại cột này là "using temporary" hay "using filesort"

Wow , nhìn lại câu query của chúng ta mới thật khủng khiếp. Không có Possible_keys nào được sử dụng, MySQL phải duyệt qua 9475 hàng mới tìm ra cái ta cần (Hãy tưởng tượng 1 Forum sẽ có đến hơn 200 000 hàng).

Bây giờ chúng ta sẽ thêm Index vào và query lại

CODE

MySQL>ALTER TABLE employee ADD INDEX(employee_number char);
MySQL>EXPLAIN SELECT employee_number,firstname,surname FROM employee WHERE employee_number= '10875';
+----------+-------+---------------+---------+---------+-------+------+-------+
| table | type | possible_keys | key | key_len | ref | rows | Extra |
+----------+-------+---------------+---------+---------+-------+------+-------+
| employee | const | PRIMARY | PRIMARY | 10 | const | 1 | |
+----------+-------+---------------+---------+---------+-------+------+-------+


Tốt hơn nhiều rồi , kiểu TYPE = Const có nghĩa rằng MySQL hiểu ra chỉ có 1 hàng đúng với ý ta, và thể hiện qua cột Rows = 1 , kiểu key= PRIMARY được sử dụng và chiều dài key_len là 10.Chỉ tìm 1 hàng tất nhiên rằng tốt hơn nhiều so với tìm 9475 hàng

Vậy câu hỏi đặt ra là , nếu tôi muốn thêm Index cho những cột mà có thể có nhiều hơn 1 kết quả khi query thì sao?
Vẫn add index như bình thường ,giả sử bạn cần tìm những người có họ là Nguyễn , tên là Nam

CODE

MySQL>ALTER TABLE employee ADD INDEX(surname,firstname);
MySQL>EXPLAIN SELECT overtime_rate FROM employee WHERE surname='Nguyễn' and firstname="Nam";
+--------+------+-------------------+---------+---------+-------+------+-----------+
| table | type | possible_keys | key | key_len | ref | rows | Extra |
+--------+------+-------------------+---------+---------+-------+------+-----------+
|employee| ref | surname,surname_2 | surname | 41 | const | 1 |where used |
+--------+------+-------------------+---------+---------+-------+------+-----------+


Tuy nhiên , nếu chỉ cần Firstname

CODE

MySQL>EXPLAIN SELECT overtime_rate FROM employee WHERE firstname='Name';
+----------+------+---------------+------+---------+------+------+------------+
| table | type | possible_keys | key | key_len | ref | rows | Extra |
+----------+------+---------------+------+---------+------+------+------------+
| employee | ALL | NULL | NULL | NULL | NULL | 9475| where used |
+----------+------+---------------+------+---------+------+------+------------+


thì MySQL sẽ tìm hết vì không hề có Index cho Firstname mà chỉ có Index cho (Surname,Firstname)


Khi nào thì cần Add Index ? Bất cứ khi nào bạn thay đổi Table bạn đều cần Add Index lại , giống như khi bạn thay đổi nội dung quyển sách , bạn cần phải làm lại mục lục. Vậy hãy cân nhắc , nếu Database của bạn sử dụng INSERT hay UPDATE nhiều hơn là SELECT thì Index chỉ làm chậm thêm mà thôi.

Có thể nhanh hơn nữa không ? Có  ! Bạn không cần phải làm Index cho cả Field mà chỉ cần 1 phần. Giống như chi tiết Mục Lục của sách mà quá dài cũng làm bạn khá vất vả, do đó họ chỉ trích dẫn 1 tựa đề. Quay lại với table của chúng ta , Surname và Firstname chỉ maximum là 40 chars , nếu chúng ta index nó , chúng ta tạo ra mỗi record đến 80 chars . Có thể tiết kiệm bằng cách sau

CODE

MySQL>ALTER TABLE employee ADD INDEX(surname(20),firstname(20));

Bây giờ thì bạn tiết kiệm được đến 50% mà vẫn đảm bảo được tốc độ rồi đó (trừ phi bạn làm Index quá ngắn). Có thể bạn nói đĩa cứng server tôi "vô tư" nhưng hãy nhớ rằng "Nhỏ hơn là nhanh hơn".

ĐIỀU KÌ DIỆU VỚI OPTIMIZE VÀ ANALYZE

"Ma thuật" của MySQL là biết cách chọn khoá (key) nào để query(nếu có). Quá trình này gọi là "query optimizer", nó sẽ "liếc" qua những Index đang có để quyết định sẽ dùng Index nào để tìm. Hãy tưởng tượng bạn đang tìm 1 dĩa CD của "Maria Carrey" có tên là "I Love You" , có nghĩa là có 2 Indexes ở đây , 1 cho tên tác giả và 1 cho tên CD. Bạn nhận thấy rằng danh mục có 20000 tên tác giả và 400000 tên Album. Một cách đơn giản ,bạn sẽ tìm theo tên tác giả. Khi có được , bạn lại thấy rằng "Maria Carrey" có 50 CDs và CD "I Love You" bắt đầu bằng chữ I. Đơn giản và dễ dàng tìm ra cái mình muốn phải không ? MySQL cũng vậy nhưng ...bạn phải chỉ cho nó bằng cách:

CODE

ANALYZE TABLE tablename;

Những lệnh DELETE và UPDATE để lại rất nhiều những khoảng trống (gaps) vô nghĩa cho table(Đặc biệt là khi bạn dùng kiểu varchar hay text/blob). Điều đó có nghĩa rằng MySQL cũng phải đọc và phân tích những thứ vô nghĩa đó khi query. Điều này được khắc phục khi bạn chạy

CODE

OPTIMIZE tablename;


Do đó 2 câu lệnh trên bạn nên chạy 1 cách thường xuyên để bảo đảm tối ưu hoá Database của mình.

Sưu tầm http://www.thienduongweb.com/home/post-tang-toc-mysql-234.html

Tối ưu hóa truy vấn MySQL cho site có lượng truy cập lớn

Mình xin bắt đầu với 1 database có bảng users với khoảng 1 triệu records, nó là kinh nghiệm mình gặt hái được trong quá trình tham gia phát triển dự án game online UGH! Thân chào các bạn Lập Trình Web!

Trong sự nghiệp lập trình web của mình, hẳn không ít coder chúng ta không có những mục tiêu, hoài bão là xây dựng, thực hiện được những dự án lớn, có tầm cỡ quốc gia, quốc tế. Chẳng hạn Vật Giá, Chợ Điện Tử, Zing, Zooz... ở Việt Nam, hay lớn hơn là những YouTube, MySpace, Facebook... trên qui mô toàn cầu.

Khi nói đến những dự án lớn thì một trong những vấn đề được các coder quan tâm hàng đầu đó là hiệu suất của dự án. Một site nhỏ với qui mô vài trăm user, dung lượng database chưa đáng kể thì thời gian truy vấn, tải trang chưa phải là vấn đề bạn cần quan tâm. Nhưng theo thời gian site phát triển với tốc độ chóng mặt, chẳng mấy chốc đã có tới hàng triệu users tham gia, tỉ lệ thuận với nó là bảng users có hàng triệu records, database phình to, dung lượng có thể lên đến hàng gigabyte, hàng chục gigabyte thậm chí hàng trăm gigabyte...  Lúc này, ngoài việc triển khai các kế hoạch kinh doanh, khai thác lợi nhuận (có thể để bộ phận kinh doanh lo) thì một vấn đề lớn đặt ra cho các coder chúng ta là làm sao để website với 1 database to như vậy vẫn chạy mượt mà như là database nhỏ!? Ngoài những vấn đề về đầu tư cơ sở hạ tầng khủng với server cấu hình cao, database server riêng rẽ, chuẩn hóa code ra mình mạo muội viết bài viết này để chúng ta cùng chia sẽ những kinh nghiệm, thủ thuật về tối ưu truy vấn MySQL với một database lớn.

Mình xin bắt đầu với 1 database có bảng users với khoảng 1 triệu records, nó là kinh nghiệm mình gặt hái được trong quá trình tham gia phát triển dự án game online UGH!

* Thủ thuật 1: INSERT
- Ngữ cảnh: chúng ta có 2 bảng users (1 triệu records), messages (empty) với cấu trúc:
users
- user_id
- name
- money
messages
- message_id
- user_id
- subject
- body

- Yêu cầu: một ngày đẹp trời, bạn muốn gửi thông điệp đến tất cả các users có số money ít hơn 1 USD rằng: Tai khoan cua ban sap het! Hay nop them tien vao tai khoan.

- Cách làm thông thường:
PHP Code:
CODE

$query = MySQL_query("SELECT * FROM users WHERE money < 1");
$subject     = "Money cua ban sap het!";
while ( $row = db_fetch_object($query) ) {
     
    $body            = $row->name ." than men! So money trong tai khoan cua ban chi con chua den 1 USD - mua duoc 1 kg rau muong luoc. Hay nop them tien vao tai khoan de giao dich khong bi gian doan.";
     
    MySQL_query("INSERT INTO messages (user_id, subject, body) VALUES ($row->user_id, '$subject', '$body')");
}
// Processed in 67.0436019897 sec  


=> Cách làm tối ưu: dùng 1 query để giải quyết tình huống này
PHP Code:

CODE

MySQL_query("
    INSERT INTO messages
    (user_id, subject, body)
    SELECT  
        user_id, 'Money cua ban sap het!', CONCAT(name, ' than men! So money trong tai khoan cua ban chi con chua den 1 USD - mua duoc 1 kg rau muong luoc. Hay nop them tien vao tai khoan de giao dich khong bi gian doan.')
    FROM users
    WHERE money < 1
");
// Processed in: 3.5900 sec  


Kết quả: thời gian xử lí giảm xuống gần 20 lần

Thủ thuật trong trường hợp này:
- Kết hợp INSERT và SELECT để thay thế cho while của PHP.
- Dùng CONCAT để lấy name của user.


* Thủ thuật 2: UPDATE
- Ngữ cảnh: có 2 bảng users (1 triệu records), user_scores (2 triệu records)
users
- user_id
- name
- total_scores
- max_scores_can_contain
user_scores
- user_score_id
- user_id
- score_type_id
- scores

- Yêu cầu: một user sẽ được cộng thêm 1 số điểm là scores trong bảng user_scores tương ứng với mỗi score_type_id (ưu tiên theo score_type_id) mà user đang có. Nhưng tổng số scores hiện có và scores của các score_type_id này không được vượt quá con số max_scores_can_contain trong bảng users, nếu vượt quá thì chỉ lấy số scores tương ứng với tổng số scores bằng max_scores_can_contain. Sao yêu cầu loằng ngoằng vậy ta ? Chắc do nó là advanced nên mới thế .

- Giải quyết vấn đề:
PHP Code:
CODE

// Query tat ca users, chi update nhung user co scores > 0
$query = MySQL_query("SELECT * FROM user_scores WHERE scores > 0");
while ( $row = MySQL_fetch_object($query) ) {
     
    // Lay object cua user nay
    $user = MySQL_fetch_object(MySQL_query("SELECT * FROM users WHERE user_id = $row->user_id"));
     
    // Chi cong nhung user cos total_scores < max_scores_can_contain
    if ( $user->total_scores < $user->max_scores_can_contain ) {         
         
        // Bat dau kiem tra bien scores_addition se cong vao
        if ( $user->total_scores + $row->scores >= $user->max_scores_can_contain ) {
            
            // Chi cong vao de total scores = max scores can contain
            $scores_addition = $user->max_scores_can_contain - $user->total_scores;
        } else {
            
            // Cong binh thuong
            $scores_addition = $row->scores;
        }
         
        // Bat dau cong
        MySQL_query("UPDATE users SET total_scores = total_scores + $scores_addition WHERE user_id = $user->user_id");
    }
}
// Processed in 530.916620016 sec  


=> Tối ưu:
PHP Code:
CODE

MySQL_query("
UPDATE users AS u
    LEFT JOIN user_scores AS us  
        ON u.user_id = us.user_id
SET u.total_scores = u.total_scores +
    (
        CASE
            WHEN (u.total_scores + us.scores) > u.max_scores_can_contain
                THEN (u.max_scores_can_contain - u.total_scores)
            ELSE us.scores
        END
    )
WHERE u.total_scores < u.max_scores_can_contain
    AND us.scores > 0     
");
// Processed in 59.2287611961 sec  

Kết quả: thời gian xử lí giảm đi gần 10 lần

Thủ thuật:
- Dùng WHEN ELSE chia case và cộng ngay trong câu truy vấn.

Ok, đây là 2 tut đầu của mình với cơ sở hạ tầng đơn giản chỉ là Xampp server được cài đặt trên laptop của mình. Có lẽ 1 phần vì cấu hình server không được gút cho lắm nên có đoạn script chạy hơi bị lâu. Không sao, điều quan trọng là chúng ta so sánh được thời gian trước và sau khi tối ưu. Còn trên thực tế với database này thì chắc là bạn đã phải sắm database server từ lâu rồi !

Mình cũng đính kèm theo source của 2 tut này http://www.mediafire.com/?lhbcwmodm9q8czo, các bạn có thể thao tác:
- Giải nén, copy thư mục này lên server, ví dụ tên thư mục là MySQL_optimize
- Tạo database MySQL_optimize
- Import file MySQL_optimize.sql vào database này
- Chỉnh lại thông số trong file config.php
- Test tutorial nào thì bỏ comment out tương ứng của tutorial đó trong file index.php, đoạn include tutorial_1.php, tutorial_2.php
- Trong file tutorial:
+ Bỏ comment out trong step 1, chạy file index.php để có sample data
+ Bỏ comment out trong step 2, chạy file index.php để có kết quả lúc chưa tối ưu
+ Bỏ comment out trong step 3, chạy file index.php để có kết quả lúc đã tối ưu

Test, so sánh và thưởng thức thành quả !

How to Optimize MySQL Queries for Speed and Performance

You can deploy fast, secure, and trusted MySQL database instances on Alibaba Cloud. Alibaba has an advanced network of cloud-based technologies and their breaking performance and flexible billing have enabled cloud without borders for its over one million paid customers. Alibaba Cloud has continued to show enormous contribution to the open-source communities and has empowered developers worldwide. Alibaba Cloud was the winner of the prestigious 2018 MySQL Corporate Contributor Award and is also a platinum sponsor of the MariaDB foundation. In this guide, we will take you through the steps of optimizing SQL queries and databases on your Alibaba Cloud Elastic Compute Service (ECS) instance. This will guarantee stability, scalability, reliability and speed of applications and websites running on your Alibaba Cloud instance. Prerequisites A valid Alibaba cloud account. If you don't have one already, you can sign up for an Alibaba Cloud and enjoy $300 worth in Free Trial. A server running your favorite operating system that can support MySQL (e.g. Ubuntu, Centos, Debian). MySQL database server. A MySQL user capable of running root commands. Tip #1: Index All Columns Used in 'where', 'order by', and 'group by' Clauses Apart from guaranteeing uniquely identifiable records, an index allows MySQL server to fetch results faster from a database. An index is also very useful when it comes to sorting records. MySQL indexes may take up more space and decrease performance on inserts, deletes, and updates. However, if your table has more than 10 rows, they can considerably reduce select query execution time. It is always advisable to test MySQL queries with a "worst case scenario" sample amount of data to get a clearer picture of how the query will behave on production. Consider a case where you are running the following SQL query from a database with 500 rows without an index: mysql> select customer_id, customer_name from customers where customer_id='140385'; The above query will force MySQL server to conduct a full table scan (start to finish) to retrieve the record that we are searching. Luckily, MySQL has a special 'EXPLAIN' statement that you can use alongside select, delete, insert, replace and update statements to analyze your queries. Once you append the query before an SQL statement, MySQL displays information from the optimizer about the intended execution plan. If we run the above SQL one more time with the explain statement, we will get a full picture of what MySQL will do to execute the query: mysql> explain select customer_id, customer_name from customers where customer_id='140385'; +----+-------------+-----------+------------+------+---------------+------+---------+------+------+----------+-------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-----------+------------+------+---------------+------+---------+------+------+----------+-------------+ | 1 | SIMPLE | customers | NULL | ALL | NULL | NULL | NULL | NULL | 500 | 10.00 | Using where | +----+-------------+-----------+------------+------+---------------+------+---------+------+------+----------+-------------+ As you can see, the optimizer has displayed very important information that can help us to fine-tune our database table. First, it is clear that MySQL will conduct a full table scan because key column is 'NULL'. Second, MySQL server has clearly indicated that it's going to conduct a full scan on the 500 rows in our database. To optimize the above query, we can just add an index to the 'customer_id' field using the below syntax: mysql> Create index customer_id ON customers (customer_Id); Query OK, 0 rows affected (0.02 sec) Records: 0 Duplicates: 0 Warnings: 0 If we run the explain statement one more time, we will get the below results: mysql> Explain select customer_id, customer_name from customers where customer_id='140385'; +----+-------------+-----------+------------+------+---------------+-------------+---------+-------+------+----------+-------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-----------+------------+------+---------------+-------------+---------+-------+------+----------+-------+ | 1 | SIMPLE | customers | NULL | ref | customer_id | customer_id | 13 | const | 1 | 100.00 | NULL | +----+-------------+-----------+------------+------+---------------+-------------+---------+-------+------+----------+-------+ From the above explain output, it's clear that MySQL server will use our index (customer_Id) to search the table. You can clearly see that the number of rows to scan will be 1. Although I run the above query in a table with 500 records, indexes can be very useful when you are querying a large dataset (e.g. a table with 1 million rows). Tip 2: Optimize Like Statements With Union Clause Sometimes, you may want to run queries using the comparison operator 'or' on different fields or columns in a particular table. When the 'or' keyword is used too much in where clause, it might make the MySQL optimizer to incorrectly choose a full table scan to retrieve a record. A union clause can make the query run faster especially if you have an index that can optimize one side of the query and a different index to optimize the other side. Example, consider a case where you are running the below query with the 'first_name' and 'last_name' indexed: mysql> select * from students where first_name like 'Ade%' or last_name like 'Ade%' ; The query above can run far much slower compared to the below query which uses a union operator merge the results of 2 separate fast queries that takes advantage of the indexes. mysql> select from students where first_name like 'Ade%' union all select from students where last_name like 'Ade%' ; Tip 3: Avoid Like Expressions With Leading Wildcards MySQL is not able to utilize indexes when there is a leading wildcard in a query. If we take our example above on the students table, a search like this will cause MySQL to perform full table scan even if you have indexed the 'first_name' field on the students table. mysql> select * from students where first_name like '%Ade' ; We can prove this using the explain keyword: mysql> explain select * from students where first_name like '%Ade' ; +----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+ | 1 | SIMPLE | students | NULL | ALL | NULL | NULL | NULL | NULL | 500 | 11.11 | Using where | +----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+ As you can see above, MySQL is going to scan all the 500 rows in our students table and make will make the query extremely slow. Tip 4: Take Advantage of MySQL Full-Text Searches If you are faced with a situation where you need to search data using wildcards and you don't want your database to underperform, you should consider using MySQL full-text search (FTS) because it is far much faster than queries using wildcard characters. Furthermore, FTS can also bring better and relevant results when you are searching a huge database. To add a full-text search index to the students sample table, we can use the below MySQL command: mysql>Alter table students ADD FULLTEXT (first_name, last_name); mysql>Select * from students where match(first_name, last_name) AGAINST ('Ade'); In the above example, we have specified the columns that we want to be matched (first_name and last_name) against our search keyword ('Ade'). If we query the optimizer about the execution plan of the above query, we will get the following results: mysql> explain Select * from students where match(first_name, last_name) AGAINST ('Ade'); +----+-------------+----------+------------+----------+---------------+------------+---------+-------+------+----------+-------------------------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+----------+------------+----------+---------------+------------+---------+-------+------+----------+-------------------------------+ | 1 | SIMPLE | students | NULL | fulltext | first_name | first_name | 0 | const | 1 | 100.00 | Using where; Ft_hints: sorted | +----+-------------+----------+------------+----------+---------------+------------+---------+-------+------+----------+-------------------------------+ It's clear that only a single row will be scanned even if our student's database has 500 rows and this will speed up the database. Tip 6: Optimize Your Database Schema Even if you optimize your MySQL queries and fail to come up with a good database structure, your database performance can still halt when your data increases. Normalize Tables First, normalize all database tables even if it will involve some trade-offs. For instance, if you are creating two tables to hold customers data and orders, you should reference the customer on the orders table using the customer id as opposed to repeating the customer's name on the orders table. The latter will cause your database to bloat. The image below refers to a database schema that is designed for performance without any data redundancy. In MySQL database normalization, you should represent a fact only once in the entire database. Don't repeat the customer name in every table; instead just use the customer_Id for reference in other tables. Image title Also, always use the same data type for storing similar values even if they are on different tables, for instance, the schema above uses 'INT' data type to store 'customer_id' both in the customers and orders table. Use Optimal Data Types MySQL supports different data types including integer, float, double, date, date_time, Varchar, and text, among others. When designing your tables, you should know that "shorter is always better." For instances, if you are designing a system user's table which will hold less than 100 users, you should use 'TINYINT' data type for the 'user_id' field because it will accommodate all your values from -128 to 128. Also, if a field expects a date value (e.g. sales_order_date), using a date_time data type will be ideal because you don't have to run complicated functions to convert the field to date when retrieving records using SQL. Use integer values if you expect all values to be numbers (e.g. in a student_id or a payment_id field). Remember, when it comes to computation, MySQL can do better with integer values as compared to text data types such as Varchar Avoid Null Values Null is the absence of any value in a column. You should avoid this kind of values whenever possible because they can harm your database results. For instance, if you want to get the sum of all orders in a database but a particular order record has a null amount, the expected result might misbehave unless you use MySQL 'ifnull' statement to return alternative value if a record is null. In some cases, you might need to define a default value for a field if records don't have to include a mandatory value for that particular column/field. Avoid Too Many Columns Wide tables can be extremely expensive and require more CPU time to process. If possible, don't go above a hundred unless your business logic specifically calls for this. Instead of creating one wide table, consider splitting it apart in to logical structures. For instance, if you are creating a customer table but you realize a customer can have multiple addresses, it is better to create a separate table for holding customers addresses that refer back to the customers table using the 'customer_id' field. Optimize Joins Always include fewer tables in your join statements. An SQL statement with poorly designed pattern that involves a lot of joins may not work well. A rule of thumb is to have utmost a dozen joins for each query. Tip 7: MySQL Query Caching If your website or application performs a lot of select queries (e.g. WordPress), you should take advantage of MySQL query caching feature. This will speed up performance when read operations are conducted. The technology works by caching the select query alongside the resulting data set. This makes the query run faster since they are fetched from memory if they are executed more than once. However, if your application updates the table frequently, this will invalidate any cached query and result set. You can check if your MySQL server has query cache enabled by running the command below: mysql> show variables like 'have_query_cache'; +------------------+-------+ | Variable_name | Value | +------------------+-------+ | have_query_cache | YES | +------------------+-------+ 1 row in set (0.00 sec) Setting the MySQL Server Query Cache You can set the MySQL query cache values by editing the configuration file ('/etc/mysql/my.cnf' or '/etc/mysql/mysql.conf.d/mysqld.cnf'). This will depend on your MySQL installation. Don't set a very large query cache size value because this will degrade the MySQL server due to cached overhead and locking. Values in the range of tens of megabytes are recommended. To check the current value, use the command below: mysql> show variables like 'query_cache_%' ; +------------------------------+----------+ | Variable_name | Value | +------------------------------+----------+ | query_cache_limit | 1048576 | | query_cache_min_res_unit | 4096 | | query_cache_size | 16777216 | | query_cache_type | OFF | | query_cache_wlock_invalidate | OFF | +------------------------------+----------+ 5 rows in set (0.00 sec) Then to adjust the values, include the following on the MySQL configuration file: query_cache_type=1 query_cache_size = 10M query_cache_limit=256k You can adjust the above values according to your server needs. The directive 'query_cache_type=1' turns MySQL caching on if it was turned off by default. The default 'query_cache_size' is 1MB and like we said above a value a range of around 10 MB is recommended. Also, the value must be over 40 KB otherwise MySQL server will throw a warning, "Query cache failed to set size". The default 'query_cache_limit' is also 1MB. This value controls the amount of individual query result that can be can be cached. Conclusion In this guide, we have shown you how to optimize your MySQL server hosted on Alibaba cloud for speed and performance. We believe that the guide will allow you to craft better queries and have a well-structured database structure that will not only be simple to maintain but also offer more stability to your software applications or website. https://dzone.com/articles/how-to-optimize-mysql-queries-for-speed-and-perfor

Thứ Tư, 5 tháng 12, 2018

How to add custom fields in OpenCart

Today we will find out how to add a new field in our OpenCart Admin. Sometimes, according to the project, we need new fields to be added – new product types, new product information that we need and want to display, new category or manufacturers fields. So lets create a new product field.
1. Database
First we need to add a field in our database where the information that we need will be stored. If you take a look to the database structure  you can see that there are a few different tables where we can add our new info. It is important for you to decide where the field will be added – if it is numerical it can be inserted in the product data table, but if it is text field and you need it translated the description table is better idea, because otherwise you have a lot of work to do to related to the translations and it is not really relevant. So when you decide where want  to insert the field we can add it to the base. The SQL statement that you need  is something like this:


ALTER TABLE  'product'  ADD  'your_field name' VARCHAR (250) NOT NULL AFTER 'model';

Of  course in accordance of your needs, you can change the table that is altered, the type of the field and where exactly in the table it will be added.
Now we have a row in our database to save the new info. It is time to create new field in the admin interface to insert this.
2.Model
As we said in the previous tutorial we have four admin folders – controller, model, language and view. Lets start from the model file to create an option for our field to be saved. In the first function INSERT INFO you should add your field


your_field name = '" . $this->db->escape($data['your_field name']) . "',
 
and then you should add the same code in the product edit funtion – UPDATE query and we are done with the model file.
3.Controller
Next one is the controller file, where we should define the new field:
$this->data['entry_your_field_name'] = 
$this->language->get('entry_your_field_name');
This is where you set the variable and where the file is getting  the language value for it.
Next piece of code that you have to add is:

1
2
3
4
5
6
7
if (isset($this->request->post['your_field name'])) {
$this->data['your_field name'] = $this->request->post['your_field name'];
} elseif (isset($product_info)) {
$this->data['your_field name'] = $product_info['your_field name'];
} else {
$this->data['your_field name'] = '';
}
4. View
Now we are able to save our new field in the database, but we need to make a visual form for this in the admin panel, so it is time to edit the view. We need the file called “product-form.tlp”. It is located in the folder admin/view/template/catalog and here are the changes that you have to make:

1
2
3
4
5
<tr>
<td><?php echo $entry_your_field name; ?></td>
<td><input type="text" name="your_field name" value="<?php echo $your_field name; ?>" /></td>
</td>
</tr>
This is the admin front-end code if your field is in “Data” tab in the product Add/Edit form. Of course if you have added the field in any other tab you should change the html around the entry to fit to the template.
And we are ready to go! Now we have a new custom field that describes our product and we can display it in the front-end of our project to add custom information about the products and why not a new functionality? I will describe how this can be done in the next tutorial and I will also provide some examples how you can use that knowledge.

OpenCart

  1. How to add custom fields in OpenCart?

Thứ Tư, 7 tháng 11, 2018

Modern Frontend Developer in 2018

Before we begin with this post, just to give you an idea about me and about this roadmap; I have been doing the Fullstack Development for the past 5 years and currently working as a lead engineer at tajawal where I have to wear many different hats. It is not only my hobby but also one of my job responsibilities to keep an eye on the trends and to keep the other developers well trained. I see a lot of confusion among the beginners (and experienced alike) when it comes to staying up to date. I had lots of friends and emails asking me for guidance back in 2017 on what should they learn if they want to be in this career. So to save myself the hassle and to help the others, I decided to prepare these charts once and for all, so that whenever somebody would ask, I would just share the link to these charts. And this is how these charts were born.
Initially they were just flat out recommendations for the tools but I decided yesterday to give them a bit more structure, add details and design them in the steps form so to give you a better idea about what to pick and in what order.
I am still working on the Backend and DevOps parts but the frontend part is ready and you can have a look at it below.

Just a random image because thumbnail needs to be a part of the article 🙉

Before I go about explaining different sections in the roadmap, let me take the time to put this disclaimer here:
The purpose of this roadmap is to give you an idea about the landscape and to guide you if you are confused about what to learn next and not to encourage you to learn what is hip and trendy. You should grow some understanding of why one tool would be better suited for some cases than the other and remember hip and trendy never means best suited for the job
So let’s get started —you can find the detailed image below, however in this article I will explain each step in the roadmap one by one also.
First thing that you would want to do is learn the basics which includes learning the basics of HTML, CSS and some familiarization with JavaScript syntax.

Learn the basics of HTML

HTML is what gives structure to your pages. Its like the human skeleton that keeps you standing. First thing that you would want to do is learn the syntax and learn everything that it has to offer. You should focus on learning the below:
  • Learn the basics and how to write semantic HTML
  • Understand how to divide page into sections and how to structure the DOM properly
Task — Once you have learnt the basics of HTML, make at least 5 HTML pages. I would recommend you to pick any website e.g. look at any github profile page or twitter’s login page. And focus on structuring the content properly. It is going to be ugly, but don’t worry about that for now and keep your main focus on proper structure.

Learn some CSS

Now that we have learnt how to prepare the skeleton for the page, its time to add some skin on top of it and to make it look beautiful. CSS — Cascading stylesheets are used to add beauty to your HTML pages.
  • First thing that you will have to do is learn about the syntax and familiarize yourself with the common CSS properties.
  • Learn about the box model and how to prepare layouts using Grid and Flexbox
  • Once you are done with that, learn how to make your websites responsive with media queries.
Task –– Once you have the basics out of the way, next thing that you should do is style the HTML pages that you made in the last step. For example if you wrote the HTML page for the Github profile, its time to apply the CSS and make it actually look like the actual Github profile page. Do so with all the 5 pages that you wrote in the previous step.

Learn the Basics of JavaScript

JavaScript is what lets you make your HTML pages more interactive. For example all these sliders, popups and toast notifications that you see on websites and when it reloads certain parts of the pages without having to reload the page, it is all done with JavaScript. In this step, you are going to learn the basics of JavaScript to prepare you for the Journey –
  • Learn the syntax and the basic constructs of the language.
  • Learn how to manipulate DOM with JavaScript e.g. how to remove some element from the page, how to add some element, adding and removing classes, applying CSS styles etc with JavaScript.
  • After you are done with that learn and understand the topics such as scopes, closures, hoisting and event bubbling etc.
  • Learn how to make HTTP calls with XHR or Ajax. Ajax is what lets you perform certain actions without reloading the page.
  • After you have learnt that now it is time to learn about all the new features in ES6+. ES6 is just a version of JavaScript which introduced lots of interesting updates to the language e.g. classes, different ways to declare variables, added new methods to arrays, string concatenation etc. Most of the articles that you will find online, they will use Babel to explain ES6 which is a transpiler that converts the new JavaScript to old JavaScript since it is not supported by the old browsers. But don’t worry about Babel for now, just get the idea about the concepts and use them in any of the latest browser which support ES6 for practicing. We will revisit ES6 later on.
You should now be feeling that the things are getting real. You need a pat on the back if you have been following along. These were some of the most important things that you have just learnt 👏

Should I learn jQuery?

There was a time when every one was crazy about jQuery and for good reasons; it was a powerful library that provided a wrapper on top of JavaScript and let you perform anything in a browser compatible way. But long gone are those days now, it isn’t being used that much for the new projects but there are still people using it. You don’t have to learn it but it is really easy and it would be beneficial for you if you want to have a look.

Time to Practice

I say this a lot and I will say it here again, you don’t learn anything without practice. You might have a momentary feeling that you understand something but it would soon go away if you don’t practice. Make sure that you practice as much as you can, while you are following this roadmap.
Go ahead and make some responsive website and add interactivity with JavaScript. You can copy any existing webpage that you might find interesting online but remember to use everything that you have learnt till this point.
Once you have made some of the websites, its time to get into the real business now. So go to github.com and search for some projects and try to open some pull requests on some open-source projects. Some of the ideas for pull requested are listed below :
  • Enhance the UI, make any demo pages responsive or improve the design
  • Look at any of the open issues that you can solve
  • Refactor any of the code that you think can be improved
Link this repo, tell them you are learning and ask for feedback on your PR and how you can improve.
While I would recommend this Github part, it needs some knowledge of git and is optional. You don’t have to do this but if you do, you will find it really beneficial — you will be amazed that how many people are willing to help you if you just ask. You can find many free resources for git, try this one.

Give yourself a pat on the Back

You have got the basics out of the way. If you have learnt everything well, you can find yourself some freelance work or maybe a full time job. However, don’t stop here, there is still a long way to go if you want to have a better career.

Package Managers

Before this point, if you were to use some external library e.g. a plugin or any external widget, you have to download the JavaScript and CSS files manually and put them in the project, and then those libraries or plugins release new versions, you have to download the newer files and put them in your projects again, which is an extreme hassle. Package managers take this hassle away from your workflow. They help you bring external libraries and plugins into your projects, so that you don’t have to worry about copying the libraries manually or go through the hassle of updating them when they release new versions. There is yarn and npm available. Both are almost same, there are only implementation, you can pick any of them and once you learnt to use one the other would be just the same.

Let’s use what we have learnt

After you have got the basic understanding of package managers, go ahead and install some external library in the webpages that you made above e.g. install some toast plugin and when user clicks a button, show him the toast message or create a login form and do the form validation using some form validation library and play with different options and see how to install different versions.
While you are at it, make sure to read about semantic versioning

CSS Preprocessors

Preprocessors enrich CSS with the functionality that it isn’t capable of by default. There are different many options Sass, Less, Stylus etc. If I were to pick one, I would go for Sass. However, PostCSS has been gaining a lot of traction lately, it is a nice-to-have and is sort of “Babel” for CSS. You can use it stand-alone or on top of Sass also. I would recommend you to learn Sass for now and revisit PostCSS later when you have time.

CSS Frameworks

You don’t need to learn CSS frameworks any more, however if you would want to pick any, there is one under every rock. The ones that I liked the most among the ones that I tried are Bootstrap, Materialize and Bulma. But if you look at their demand in market I would pick Bootstrap if I was starting today.

CSS Organization

As your applications grow, CSS start to become messy and unmaintainable. There are multiple ways to structure your CSS better for scalability e.g. there is OOCSS, SMACSS, SUITCSS, Atomic and BEM. You should know about the differences between them but I prefer BEM.

Build Tools

Tools to help you in the building/bundling and development of JavaScript applications. This category includes linters, task runners and bundlers.
For task runners, there used to be different many options including npm scripts, gulp, grunt etc. But at this time, since webpack lets you handle most of the stuff that we used to do with gulp, there is only npm scripts in the task runners now which you can use to automate the tasks that webpack might be capable of doing. You don’t need to learn Gulp, however later on if you find some time, feel free to have a look at it and see if it can help you in your application.
For the linters, again there used to be many options including ESLint, JSLint, JSHint and JSCS. But currently there is mostly ESLint so go for it.
For the module bundlers, again several different options including Parcel, Webpack, Rollup, Browserify etc. If you have to pick one, close your eyes and pick Webpack for now. Rollup is quite common also but it is recommended to be used mostly for the libraries; when it comes to apps, there is webpack. So teach yourself webpack for now and revisit this section for Rollup later on if you want to.

Time to Practice — Create something

Congrats! You can call yourself 75% modern JavaScript developer now. Now go ahead and create something with all that you have learnt. Maybe create some sort of library in which you have to use Sass and JavaScript. Then use Webpack to convert Sass to CSS and use babel in it to transpile ES6 code. Once you are done with, release it on Github and npm.

Pick a Framework

In the old roadmap, this section used to be next to the basics but I changed it to be after Sass, build tools and package managers because you will be using all of that in the frameworks and without the knowledge, it might seem scary to you.
Again in frameworks, there are several options. But commonly used one these days are React, Vue and Angular. There is more and more demand for React.js these days. However, you can pick any of the listed ones and you will be fine. Personally I would pick React or Angular. Just a quick note here, as a beginner you might find Angular to be a bit easier comparatively, probably because it supports almost everything out of the box e.g. powerful router with support for lazy loading, HTTP client with support for interceptors, dependency injection, component CSS encapsulation etc without having to worry about picking external libraries. But React definitely has an upper hand looking at the community around it and the way team at facebook has been working to improve it. Just make sure to not pick anything because of the hype of it, google it, compare and see what suites you best.
I will leave the comparison and my personal experience with both for another post but since this post is about learning, here is how you might find the learning curves for Angular and React
Learn curves in the graph below consider the fact that you already have an understanding of TypeScript and basic idea of Rx.JS. For the “why” I will cover that in some future post but mainly it is because of some of the standardization and some of the key features that angular provides out of the box. But that doesn’t mean React is bad, both have their own place, I will cover that extensively in some upcoming post.
Have a look at both and see what suites you best.
Once you have made your choice for framework, there are certain other things that you might have to learn. For example if you decided to go with React; you might have to learn Redux or Mobx for the state management, depending upon the size of application that you will be working. Mobx is suitable for small to mid-sized applications, Redux is more suitable for larger scale applications. And you might even not need any of them and depend upon the native state management in React if your app allows that.
If you pick Angular, you will have to do TypeScript (you can develop angular applications without it also but it is recommended to use it) and Rx.js which will also benefit you out of your Angular applications. It is a really powerful library and is also suitable for functional programming.
And if you pick Vue.js, you might have to learn Vuex which is sort of similar to Redux but for Vue.
You should note that, Redux, Mobx and Rx.js are not just bound to these frameworks, you can use these out in your vanilla JavaScript apps also. Also, if you pick Angular from the list, make sure it is Angular 2+ and not Angular 1+

Time to Practice

Now you know _everything_ that one might need to build a modern JavaScript application. Go ahead and make some application with whatever framework you picked. You can find some of the ideas in the ideas directory in the repository; pick anything and start!
And once you are done making, read about how to measure and improve performance. For example look at Interactivity Time, Page Speed Index, and Lighthouse Score etc

Progressive WebApps

And once you are done with all of steps listed above, learn about service workers and how to make progress web apps.

Testing your Apps

There are lots and lots of different tools for different purposes. I mostly find myself using a combination of Jest, Mocha, Karma and Enzyme. However, before you jump and pick any, it would be better if you first understand the different testing types, look at all the options available and use the ones most suitable for your needs.
Here is a really nice summary to get you started

Static Type Checkers

Static type checkers help you to add type checking to JavaScript. You don’t need to learn these but they really give you superpowers and can be learnt in a few hours and then you can keep . There is mainly TypeScript and Flow. I love TypeScript and would pick it but feel free to check both and pick one of your liking.

Server Side Rendering

The skills that you have got till this point should be sufficient to get you a position for any of the “Frontend Engineering” roles. But don’t stop here!
Learn about server side rendering in whatever framework you picked. There are different options, depending on what framework you are using. For example if you decided to use React, most notable options are Next.js and After.js. For angular, there is Universal. And for Vue.js there is Nuxt.js.
There could be things still missing in the roadmap but this is all of what you need for any “Frontend Engineering” role. And remember the key is to practicing as much as you can. It will look scarier in the beginning and you will feel like you are not grasping but that is normal and over time you will feel that you are getting better and better. And don’t forget to ask for help if you are stuck, you will be amazed by how much people are willing to help ..or at least I am 😉
Feel free to befriend me on twitter or say hi by email. And with that this post comes to an end. Until next time, stay tuned!

Sưu tầm: Modern Frontend Developer in 2018

Khác biệt giữa HTML và HTML5

khác biệt giữa html và html5

Giới thiệu

Những ai mới vào thế giới thiết kế web có thể thường nghe từ “Markup” và tự hỏi nó có nghĩa gì, và khác gì so với từ “code”. Trước đây, ngôn ngữ markup được thiết kế để xử lý, định nghĩa và hiển thị văn bản; nhung tag và chạy chữ với style để giúp dễ đọc cho máy tính. Về lịch sử, ngôn ngữ markup lấy cảm hứng từ process của manuscript marking-up qua hướng dẫn của máy in, được lấy từ markups viết tay. HTML là một ngôn ngữ markup nổi tiếng nhất được dùng. Trong vài năm trở lại đây, một bản cập nhật cho ngôn ngữ này là HTML5 được xuất bản. Trong bài hướng dẫn, chúng tôi sẽ cung cấp sự khác biệt giữa HTML và HTML5.

HTML là gì?

HTML hoặc Hyper-Text Markup Language có thể được hiểu là ngôn ngữ chính của WordWide Web. Hầu hết những trang web được host trên mạng đều được viết bởi vài phiên bản của HTML. Qua HTML, lập trình viên có thể đảm bảo chắc chắn làm thế nào để  multimedia, văn bản và hyperlink giữa chúng hiển thị trên trình duyệt web. Từ những elements mà kết nối đến văn bản của bạn (hypertext) tới việc giúp những tài liệu này tương tác được (ví dụ: forms); tất cả là thành phần của HTML.
Chuẩn HTML được phát triển bởi W3C (World Wide Web Consortium) vào năm 1997. Trong HTML, tags được dùng để định nghĩa cấu trúc văn bản; tags, và elements được định nghĩa bằng ký tự < và >. Một vài ví dụ trước có đề cập đến tags là headings, tables, và paragraph, vâng vâng. Trình duyệt chịu trách nhiệm để reder một trang web qua những tags này. Từ đó, HTML là chuẩn duy nhất để phát triển web. Trong những ngày đầu tiên, tất cả nội dung và style tags được dồn vào một ngôn ngữ lớn, phức tạp. Qua thời gian, W3C quyết định tách nội dung và style của một trang web vì nghĩ nó cần thiết; việc này dẫn đến sự bắt đầu của style sheets. Ngày nay, tags được dùng để định nghĩa style của một văn bản (ví dụ: FONT) đã lỗi thời vì mọi người thích style sheets và chỉ còn có tag định nghĩa nội dung (ví dụ H1) là còn tồn tại như là một thành phần cốt lõi của HTML.
HTML được cập nhật nhiều qua thời gian, và hiện tại, chuẩn HTML mới nhất là HTML5. HTML5 tất nhiên vẫn là ngôn ngữ markup chính, nhưng nó cung cấp thêm nhiều tính năng hơn HTML và đã xóa một số tính nghiêm ngặt thường thấy trong XHTML. Hằng ngày, tính năng mới được thêm vào HTML5, nhưng vẫn chưa có phiên bản mới được triển khai. Khác biệt cơ bản giữa HTML và HTML5 có thể hiểu là bất kể hình hay tiếng đều không phải là thành phần chính của HTML trong khi đó, cả hai có thể được xem phần bổ sung của HTML5.
History of HTML

Khác biệt chính giữa HTML và HTML5

Một điều chắc chắn về mảng công nghệ thông tin là các cập nhật/thay đổi định kỳ là chắc chắn xảy ra. Không ngôn ngữ nào có thể tồn tại mà không có phiên bản mới. HTML cũng không ngoại lệ. HTML5 được phát hành với mục đích chính là cải thiện trải nghiệm người dùng World Wide Web. Như đã nhắc ở phần trước, thuận lợi lớn nhất của HTML5 khiến nó vượt hơn các phiên bản không tên khác là nó có audio phiên bản cao và hỗ trợ video, vốn không phải là thành phấn chính của các phiên bản HTMLs trước. các khác biệt giữa HTML và HTML5:
  • SVG, canvas và những hình dạng vector đều được hỗ trợ bởi HTML5, khi HTML nếu muốn sử dụng hình vector chỉ có thể dùng nó trong một công nghệ khác như, Flash, VML và silver light.
  • HTML5 sử dụng web SQL databases, application cache để lưu dữ liệu tạm, trong khi đó, HTML chỉ có cache của trình duyệt được dùng cho mục đích này.
  • Một khác biệt nữa giữa HTML và HTML5 đáng nhắc đến là HTML không cho phép JavaScript chạy trong web browser (thay vì vậy nó chạy trong interface thread của browser), trong khi đó HTML5 hỗ trợ hoàn toàn cho JavaScript để chạy nền (nhờ vào JS web worker API của HTML5).
  • HTML5 không dựa trên SGML, cho phép nó tăng luật parsing, có thể tương thích mạnh mẽ hơn
  • Trong HTML5, inline MathML và SVG có thể được dùng trong văn bản nơi mà không được hỗ trợ trong HTML.
  • Một số elements lỗi thời đã bị loại bỏ hoàn toàn là: isindex, noframes, acronym, applet, basefont, dir, font, frame, frameset, big, center, strike, tt.
  • HTML5 hỗ trợ nhiều loại điều khiển form, ví dụ: ngày giờ, email, số lượng, khoảng, số điện thoại, URL, tìm kiếm, vâng vâng
  • Có nhiều element được giới thiệu trong HTML. Một vài trong số chúng là quan trọng nhất: summary, time, aside, audio, command, data, datalist, details, embed, wbr, figcaption, figure, footer, header, article, hgroup, bdi, canvas, keygen, mark, meter, nav, output, progress, rp, rt, ruby, section, source, track, video.
Difference Between HTML and HTML5

Các Ưu điểm được cung cấp bởi HTML5 cho lập trình viên.

HTML5 muốn lập trình viên có nhiều hơn sự linh hoạt trong việc thiết kế website và có rất nhiều cải tiến mạnh mẽ đáng để nhắc đến như sau:

1. Persistent error handling: 

Hầu hết các trình duyệt đều hỗ trợ parse cho những cấu trúc không chính xác của HTML code, nhưng nhiều năm về trước, không có chuẩn nào để xử lý việc này. Có nghĩa là lập trình viên khi gặp trình duyệt mới phải tự kiểm tra HTML trên các trình duyệt để đảm bảo lỗi có thể được xử lý bởi nhiều kiến trúc khác nhau. Vì vậy, sự đồng nhất về khả năng xử lý lỗi của HTML5 là một khác biệt và lợi thế rất lớn trong vấn đề này. Sự tối ưu trong thuật toán parsing được dùng trên HTML5 là một lợi thế không thể đếm được. Thống kê cho thấy gần 90% website có thể có lỗi về coding cho nên việc xử lý những lỗi như vậy là rấ quan trọng. Hơn nữa, quản lý lỗi cũng tiết kiệm được chi phí và thời gian cho lập trình viên.

2. Cải thiện ngữ nghĩa cho elements: 

Để cải thiện lỗi code, ,To enhance code insinuation, một số cải tiến đã được thực thiện cho vai trò ngữ nghĩa của một số elements đã có sẵn. Section, article, nav và header là những element mới đã thay thế hầu hết các element div cũ, và việc này cũng giúp ích rất nhiều cho việc quét lỗi, vì nó đỡ phức tạp hơn nhiều.

3. Tăng tính tương thích cho ứng dụng web:

Một trong số các mục đích chính của HTML5 là cho phép trình duyệt xử lý như là một nền tảng ứng dụng. Website trong quá khứ ít phức tạp hơn nhưng qua thời gian, đòi hỏi cũng tăng lênh. HTML5 cho phép lập trình viên tăng quyền quản trị của hiệu năng website. Trong quá khứ, lập trình viên phải dùng rất nhiều phương thức khác nhau vì hạn chế về công nghệ phía server và browser extension chưa có. Bây giờ, với HTML5, không cần phải sử dụng JS hoặc Flash để chạy nữa (như đã từng phải làm với HTML4) vì các element hiện diện trong HTML5 đã có khả năng thực thi tất cả chức năng.

4. Dựng web mobile dễ dàng hơn:

Kể cả bây giờ, tạo một phiên bản mobile cho website cũng có thể khiến lập trình viên đau đầu. Nhân khẩu của việc sở hữu điện thoại di động đã bùng nổ trong thập kỷ qua, tạo nên một nhu cầu thực sự cho việc nâng cấp chuẩn HTML. Người dùng cuối muốn có thể truy cập web bất kỳ lúc nào với bất kỳ thiết bị nào, cho nên việc có một website responsive là cần thiết. HTML5 hỗ trợ rất nhiều cho di động, vì có thể phục vụ cho các thiết bị điện tử này.

5. Canvas element:

Một tính năng được nhắc đến nhiều nhất của HTML là element <canvas>. Tag độc nhất này đã gây ra ảnh hưởng lớn cho Adobe Flash. Kể cả khi có rất nhiều website vẫn sử dụng Flash, HTML5 vẫn khiến cho nhiều người yêu thích hơn, tin hay không, Flash sẽ sớm trở nên lỗi thời.
Sử dụng canvas element, lập trình viên có thể vẽ đồ họa sử dụng nhiều màu và hình dạng khác nhau chỉ bằng cách dùng script  (ví dụ: JavaScript). Cũng cần biết là canvas chỉ là graphic container để định nghĩa hình ảnh, một script cần phải được thực thi. Ví dụ khi mà JavaScript được dùng chung với canvas là:
<canvas id=”TestCanvas” width=”200″ height=”100″></canvas>
 var c = document.getElementById(“TestCanvas”);
    
 var context = c.getContext(“2d”);
    
 context.fillStyle = “#FF0000”;
    
 context.fillRect(0,0,140,75);

6. The Menu element:

Element mới thêm là <menu> và <menuitem> là thành phần tương tác được, chuyên dùng nhưng không hay được bàn đến trong cộng đồng lập trình viên. Tuy nhiên, những element này có thể được dùng để đảm bảo khả năng tương tác của web.
<menu> tag được dùng để đại diện cho lệnh menu trong mobile hoặc desktop application vì tính đơn giản. Cách dùng có thể là:
    <body contextmenu=”new-menu”>
        
     <menu id=” new-menu” type=”context”>
        
     <menuitem>Hello!</menuitem>
      
     </menu>
    </body>

7. Data Attributes có thể được tùy chỉnh:

Bạn có thể thêm attributes tùy ý trước khi có HTML5, nhưng rất khó, ví dụ, trong HTML4, custom attributes sẽ đôi khi làm tắt trang của bạn hoàn toàn, và chúng có thể thường gây xung đột dữ liệu. Dữ liệu data-* attribute trong HTML5 đã khắc phục được việc này. Có rất nhiều cách dùng cho attribute này, nhưng cái chính là làm nơi chưa thông tin của các elements khác nhau. Bây giờ, custom data có thể được thêm vào, nó cũng giúp lập trình viên tăng cơ hội tạo một trang web tương tác tốt và hiệu quả cao mà không cần phải tìm hiểu về server hoặc call Ajax.

8. Tạm biệt cookies:

Local storage là một nâng cấp cực lớn của HTML5. Trong những ngày trước-HTML5, nếu lập trình viên muốn lưu bất kỳ thông tin nào, họ phải tạo cookies. Cookies có thể lưu một vài loại dữ liệu (chưa kể, mọi người ghét chúng) và điều này làm localstorage trở nên có nhiều lợi thế hơn so với HTML5. localStorage object là một phần của global windows namespace và có thể được truy cập bất kỳ đâu nếu muốn qua scripts.

Thủ thuật HTML5

Thủ thuật HTML5 có thể giúp ích rất nhiều nếu bạn vừa mới bắt đầu học ngôn ngữ mới. Sử dụng những style sheet HTML5 bên dưới và bắt đầu dùng HTML. Bài thủ thuật này có tất cả những tag phổ biến nhất của HTML (bao gồm HTML5)
HTML5 Cheat Sheet

Ưu điểm của HTML5 cho người dùng cuối

HTML5 mang lại trải nghiệm hoàn toàn mới cho cả lập trình viên lẫn người dùng cuối. Một số ưu điểm nổi trội cho người dùng cuối là:
  1. Mobile browser hiện giờ đã tốt hơn rất nhiều, nhờ vào công nghệ HTML5, so với trước đây khi mà phát triển web dựa trên HTML.
  2. Phụ thuộc vào website di động là rất cao, lên tới 30% lượng người dùng ghét ứng dụng. Vì vậy nếu một user muốn sử dụng dịch vụ của một công ty, nhưng không muốn tải ứng dụng, họ chỉ cần truy cập vào website.
  3. Việc loại bỏ Adobe Flash giúp cho lập trình viên cung cấp trải nghiệm tốt hơn cho người dùng. Sử dụng JavaScript và MPEG4 liên kết với HTML5 giúp cuộc sống trở nên tốt đẹp hơn cho tất cả mọi người.
  4. Khả năng hỗ trợ audio và video element gốc có nghĩa là user không phải tải plugin đi kèm để xem multimedia trên website. Việc hỗ trợ hoàn toàn cho media khiến HTML5 trở thành lý do chính nó được dùng nhiều hơn HTML ngày nay.

Kết luận

Một phiên bản mới của bất kỳ ngôn ngữ nào cũng tốt hơn, và HTML5 là một minh chứng tốt nhất. Với mỗi năm trôi qua, lập trình viên sẽ càng cái thiện, tận dụng ưu thế của HTML5. Hơn nữa, social media cũng được trông đợi sẽ làm thay đổi hơn nữa ngôn ngữ này.
Khi làn sóng thay đổi tấn công nhiều lập trình viên trên thế giới, có thể thấy được sự tích hợp HTML5 sẽ ngày càng nhay. Để tối ưu hiệu suất của những trình duyệt tân tiến ngày nay, hãy sử dụng HTML5 sớm nhất có thể.
Sưu tầm từ Khác biệt chính giữa HTML và HTML5