List of SQL Statements from CodeAcedemy

SQL, ‘Structured Query Language’, is a programming language designed to manage data stored in relational databases. SQL operates through simple, declarative statements. This keeps data accurate and secure, and helps maintain the integrity of databases, regardless of size.

Here’s an appendix of commonly used commands.

Commands

ALTER TABLE

ALTER TABLE table_name ADD column datatype;

ALTER TABLE lets you add columns to a table in a database.

AND

SELECT column_name(s)
FROM table_name
WHERE column_1 = value_1
AND column_2 = value_2;

AND is an operator that combines two conditions. Both conditions must be true for the row to be included in the result set.

AS

SELECT column_name AS 'Alias'
FROM table_name;

AS is a keyword in SQL that allows you to rename a column or table using an alias.

AVG

SELECT AVG(column_name)
FROM table_name;

AVG() is an aggregate function that returns the average value for a numeric column.

BETWEEN

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value_1 AND value_2;

The BETWEEN operator is used to filter the result set within a certain range. The values can be numbers, text or dates.

COUNT

SELECT COUNT(column_name)
FROM table_name;

COUNT() is a function that takes the name of a column as an argument and counts the number of rows where the column is not NULL.

CREATE TABLE

CREATE TABLE table_name (column_1 datatype, column_2 datatype, column_3 datatype);

CREATE TABLE creates a new table in the database. It allows you to specify the name of the table and the name of each column in the table.

DELETE

DELETE FROM table_name WHERE some_column = some_value;

DELETE statements are used to remove rows from a table.

GROUP BY

SELECT COUNT(*)
FROM table_name
GROUP BY column_name;

GROUP BY is a clause in SQL that is only used with aggregate functions. It is used in collaboration with the SELECT statement to arrange identical data into groups.

INNER JOIN

SELECT column_name(s) FROM table_1
JOIN table_2
ON table_1.column_name = table_2.column_name;

An inner join will combine rows from different tables if the join condition is true.

INSERT

INSERT INTO table_name (column_1, column_2, column_3) VALUES (value_1, 'value_2', value_3);

INSERT statements are used to add a new row to a table.

LIKE

SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;

LIKE is a special operator used with the WHERE clause to search for a specific pattern in a column.

LIMIT

SELECT column_name(s)
FROM table_name
LIMIT number;

LIMIT is a clause that lets you specify the maximum number of rows the result set will have.

MAX

SELECT MAX(column_name)
FROM table_name;

MAX() is a function that takes the name of a column as an argument and returns the largest value in that column.

MIN

SELECT MIN(column_name)
FROM table_name;

MIN() is a function that takes the name of a column as an argument and returns the smallest value in that column.

OR

SELECT column_name
FROM table_name
WHERE column_name = value_1
OR column_name = value_2;

OR is an operator that filters the result set to only include rows where either condition is true.

ORDER BY

SELECT column_name
FROM table_name
ORDER BY column_name ASC|DESC;

ORDER BY is a clause that indicates you want to sort the result set by a particular column either alphabetically or numerically.

OUTER JOIN

SELECT column_name(s) FROM table_1
LEFT JOIN table_2
ON table_1.column_name = table_2.column_name;

An outer join will combine rows from different tables even if the the join condition is not met. Every row in the left table is returned in the result set, and if the join condition is not met, then NULL values are used to fill in the columns from the righttable.

ROUND

SELECT ROUND(column_name, integer)
FROM table_name;

ROUND() is a function that takes a column name and an integer as an argument. It rounds the values in the column to the number of decimal places specified by the integer.

SELECT

SELECT column_name FROM table_name;

SELECT statements are used to fetch data from a database. Every query will begin with SELECT.

SELECT DISTINCT

SELECT DISTINCT column_name FROM table_name;

SELECT DISTINCT specifies that the statement is going to be a query that returns unique values in the specified column(s).

SUM

SELECT SUM(column_name)
FROM table_name;

SUM() is a function that takes the name of a column as an argument and returns the sum of all the values in that column.

UPDATE

UPDATE table_name
SET some_column = some_value
WHERE some_column = some_value;

UPDATE statments allow you to edit rows in a table.

WHERE

SELECT column_name(s)
FROM table_name
WHERE column_name operator value;

WHERE is a clause that indicates you want to filter the result set to include only rows where the following condition is true.

Background to Relational Database Management Systems (RDBMS)

Relational Database Management Systems (RDBMS)

A relational database management system (RDBMS) is a program that lets you create, update, and administer a relational database. Most relational database management systems use SQL to access the database.

There are more similarities than differences between the different RDBMS, but the SQL syntax may be slightly different depending on which RDBMS you are using.

Here is a brief description of popular types of RDBMS

SQLite

SQLite is a popular open source SQL database. It is able to store an entire database in a single file. One of the biggest advantages this provides is that all of the data can be stored locally without having to connect your database to a server.

SQLite is a popular choice for databases in cellphones, PDAs, MP3 players, set-top boxes, and other electronic gadgets. The SQL course on Codecademy also uses SQLite.

MySQL

MySQL is the most popular open source SQL database. It is typically used for web application development, and often accessed using PHP.

The main advantages of MySQL are that it is easy to use, inexpensive, reliable (has been around since 1995) and has a large community of developers who can help answer questions.

Some of the disadvantages are that it has been known to suffer from poor performance when scaling, open source development has lagged since Oracle has taken control of MySQL, and it does not include some advanced features that developers may be used to.

PostgreSQL

PostgreSQL is an open source SQL database that is not controlled by any corporation. It is typically used for web application development.

PostgreSQL shares many of the same advantages of MySQL. It is easy to use, inexpensive, reliable, and has a large community of developers. It also provides some additional features such as foreign key support without requiring complex configuration.

The main disadvantage of PostgreSQL is that it is slower in performance than other databases such as MySQL. It is also less popular than MySQL which makes it harder to come by hosts or service providers that offer managed PostgreSQL instances.

Oracle DB

Oracle DB is owned by the Oracle corporation and the code is not open sourced.

Oracle is used for large applications, particularly in the banking industry. Most of the world’s top banks run Oracle applications because Oracle offers a powerful combination of technology and comprehensive, pre-integrated business applications, including key functionality built specifically for banks.

The main disadvantage of using Oracle is that it is not free to use like its open source competitors and can be quite expensive.

SQL Server

SQL Server is owned by Microsoft. Like Oracle DB, the code is also close sourced.

SQL Server is mainly used by large enterprise applications. The major difference between Oracle and SQL Server is that SQL Server only supports the Windows Operating System.

Microsoft offers a free entry level version called Express, but can become very expensive as you scale your application.

Configure htacess to block IPs entire country

​Blocking an entire country stops most traffic coming from their IP ranges.
This method isn’t 100% because some countries have slightly overlapping IP ranges.

Alternatively, you can select a single country and DENY access from all other
countries to completely block access from the rest of the world. Due to overlapping
border ranges, selecting some neighbors is recommended such as US and CA as a pair.

http://incredibill.me/htaccess-block-country-ips

More can follow:

configure non-www to www

## Redirect from non-www to www (remove the two lines below to enable)
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

What is Apache, MySQL & PHP

Install Linux LAMP Setup

LAMP Setup in Linux

What is Apache?

Apache is an open source freely available HTTP web server that runs on most UNIX-based operating systems as well as on Windows. Apache web server is used to serve web pages like (.htm .php .pl .cgi .js) etc. As per March 2012, Apache web server runs on almost 65.24% websites across all the domains.

What is MySQL?

MySQL is one of the world’s most popular open source relational database management system (RDBMS) that runs any server by providing multi-user access to multiple databases. MySQL runs with Apache.

What is PHP?

PHP (Hypertext Preprocessor) is an open source server-side scripting language that is best suited for web development and can be used to produce dynamic web pages for a website.

​Managing MySQL Users

.
.
.

In MySQL, you can create user accounts with different privileges. Privileges can vary from accessing several databases to accessing only one column in a table.

Root User

By default, MySQL has a super user that has all the privileges called root. You need to log in as root for executing many MySQL administrative tasks including managing users.
Changing Root Password

If you didn’t specifically set the root password when installing MySQL, most of the times it would be empty. If the root password is empty, make sure to reset it with a proper password for better security.

In command-line, you can use following command to change root password. Type your preferred password in place of newpassword. After hitting Enter key, it will ask to enter current password. If current password is empty, just hit Enter key.
#mysqladmin -u root -p password ‘newpassword’
Logging as a User

Use following command to log in as root user. For logging as a different user, type that username in place of root. After hitting Enter key, it will ask to enter the password. After entering correct password, you would see MySQL prompt (mysql>) where you can enter MySQL commands.
#mysql -u root -p

Viewing Existing Users
MySQL user details are stored in a table called user of a default database called mysql. In this user table, usernames are stored in a column called user and corresponding host names are stored in a column called host.

Based on these facts, you can use following SQL command to view username and host of existing users. You need to log in as root first.
#SELECT user, host FROM mysql.user;

Creating a New User
For creating a user called robin with the password robin123 at localhost (is the default host most of the time), log in as root and use following command.
#CREATE USER ‘robin’@’localhost’ IDENTIFIED BY ‘robin123’;

Granting Privileges to a User
MySQL has a series of privileges. For a general PHP application, you only need a user with SELECT, INSERT, UPDATE and DELETE privileges for the database you chose. You can grant these privileges to a user called ronbin for a database called my_database using following command.
#GRANT SELECT, INSERT, UPDATE, DELETE ON my_database.* TO ‘robin’@’localhost’;

To grant all the privileges, use ALL as below.
#GRANT ALL ON my_database.* TO ‘robin’@’localhost’;
Changing a User Password

To change the password of a user called robin to robin456, login as root user and use following command.
#SET PASSWORD FOR ‘robin’@’localhost’ = PASSWORD(‘robin456’);

Deleting a User
Log in as root and use following command to delete user robin.
#DROP USER robin@localhost;

Be careful when you delete a user since applications that used the credentials of deleted user may malfunction.

Summary
PHP needs the host name, username and password of a privileged MySQL user to connect to a MySQL database. When it comes to production level PHP applications, instead of using root user, it’s a good practice to use a dedicated user with only the required privileges for improved security.

You will only need to deal with MySQL users when you manage your own web server or when you develop web applications locally. If you are on a shared web hosting environment, most of the time, you will be provided privileged MySQL user accounts or a GUI tool to manage MySQL users.
– See more at: http://www.phpknowhow.com/mysql/managing-mysql-users/#sthash.9hMl3X3E.dpuf

WHY VAGRANT?

Vagrant provides easy to configure, reproducible, and portable work environments built on top of industry-standard technology and controlled by a single consistent workflow to help maximize the productivity and flexibility of you and your team.

To achieve its magic, Vagrant stands on the shoulders of giants. Machines are provisioned on top of VirtualBox, VMware, AWS, or any other provider. Then, industry-standard provisioning tools such as shell scripts, Chef, or Puppet, can be used to automatically install and configure software on the machine.

HOW VAGRANT BENEFITS YOU

If you’re a developer, Vagrant will isolate dependencies and their configuration within a single disposable, consistent environment, without sacrificing any of the tools you’re used to working with (editors, browsers, debuggers, etc.). Once you or someone else creates a singleVagrantfile, you just need to vagrant up and everything is installed and configured for you to work. Other members of your team create their development environments from the same configuration, so whether you’re working on Linux, Mac OS X, or Windows, all your team members are running code in the same environment, against the same dependencies, all configured the same way. Say goodbye to "works on my machine" bugs.

If you’re an operations engineer, Vagrant gives you a disposable environment and consistent workflow for developing and testing infrastructure management scripts. You can quickly test things like shell scripts, Chef cookbooks, Puppet modules, and more using local virtualization such as VirtualBox or VMware. Then, with the same configuration, you can test these scripts on remote clouds such as AWS or RackSpace with the same workflow. Ditch your custom scripts to recycle EC2 instances, stop juggling SSH prompts to various machines, and start using Vagrant to bring sanity to your life.

If you’re a designer, Vagrant will automatically set everything up that is required for that web app in order for you to focus on doing what you do best: design. Once a developer configures Vagrant, you don’t need to worry about how to get that app running ever again. No more bothering other developers to help you fix your environment so you can test designs. Just check out the code, vagrant up, and start designing.

Find more: https://docs.vagrantup.com/v2/why-vagrant/

How to backup (export) MySQL database using HeidiSQL

do not use more than one "!" in post titles.

in heidisql:
right click on database in tree on the left.
select "Export database as SQL"
in the dialog, on the right select
Database(s) [x] Create box
Table(s) [x] Create box
Data: select INSERT
Output: select One big file
FileName: click on small disk symbol at right edge to select the name and location (path) where output file is to be stored
click "Export" button (lower right)

then
transfer output file to new PC
start heidisql
select from Menu "Tools" / "Load SQL file…"
in open dialog, select the transferred .sql file
after file has loadled into the upper pane, press F9

that should be it.

By vichhaiy Posted in DB, WEP

15 Tips to Optimize Your PHP Script for Better Performance for Developers

If you are a developer, it is essential for you to optimize your script early in the development process itself. Following the best practices while coding your PHP script is a good starting point to write a well optimized PHP code.

This tutorial provides few tips to optimize PHP code from a developer point of view.

1. Use Native PHP Functions

As much as possible, try to use native PHP functions rather than writing your own functions to achieve the objective. For example, you can use range( b, k) to get an array of alphabets starting from b to k in sequence, if it is only needed once in the script rather than declaring an array with these values in a function and returning it on its call.

2. Use Single Quotes

Using single quotes ( ‘ ‘ ) is faster than using double quotes( ” ” ) if you are going to keep only the string inside it avoiding any variables. Double quotes checks for the presence of variable and adds little bit of overhead.

3. Use = = =

Use “= = =” instead of “= =”, as the former strictly checks for a closed range which makes it faster.

4. Use Appropriate Str Functions

str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4.

5. Calculate Only Once

Calculate and assign the value to the variable if that value is getting used numerous time rather than calculating it again and again where it is being used.

For example, the following will degrade the performance.

 for( $i=0; i< count($arrA); $i++){ echo count($arrA); } 

The script below will perform much better.

 $len = count($arrA); for( $i=0; i< $len; $i++){ echo $len; } 

6. Pass Reference to Function

Pass reference to the function if it does not affect your logic. A function manipulating the reference is faster than those manipulating the value been passed as here one more copy of the value is getting created. Especially it adds overhead when the value passed by you is a big array.

For example, let us create a function in two different way to increment by 1, each element of an array having values 0 to 99.

 <?php // passing by reference function computeValue( &$param ){ // Something goes here foreach( $param as $k => $value){ $param[$k] = $value + 1; } } $x = array(); for( $i =0; $i<99; $i++){ $x[$i] = $i; } computeValue( $x); // array with 100 elements each incremented by 1 print_r( $x ); ?> 

The function above works faster than the function below although both will produce the same result ( increment each element of the array by 1. )

 <?php // passing by value function computeValue( $param ){ // Something goes here foreach( $param as $k => $value){ $param[$k] = $value + 1; } return $param; } $x = array(); for( $i =0; $i<99; $i++){ $x[$i] = $i; } // array with 100 elements each incremented by 1 print_r(computeValue( $x)); ?> 

7. Create Classes Only When its Required

Don’t create classes and method until and unless its really needed, used and reused as well.

8. Disable Debugging Messages

File operations are expensive. So, if you have written lot of custom functions to log errors and warning during your development process, make sure you remove them before you push the code to production.

9. Use Caching Techniques

Use cache to reduce the load of database operations as well as the script compilation. We can use memcache for the reducing database load and APC for opcode caching and intermediate code optimization.

10. Close the Connection

Get into the habit to unset the variables and close database connection in your PHP code. It saves memory.

11. Reduce Number of Hits to DB

Try to reduce the number of hits to the database. Make queries aggregate so that you call the database less number of times. For example:

 <?php $con=mysqli_connect("localhost","username","somepassword","anydb"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL" ; mysqli_connect_error(); } function insertValue( $val ){ mysqli_query($con,"INSERT INTO tableX (someInteger) VALUES ( $val )"); } for( $i =0; $i<99; $i++){ // Calling function to execute query one by one insertValue( $i ); } // Closing the connection as best practice mysqli_close($con); ?> 

The script above is much slower than the script below:

 <?php $con=mysqli_connect("localhost","username","somepassword","anydb"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL" ; mysqli_connect_error(); } function insertValues( $val ){ // Creating query for inserting complete array in single execution. $query= " INSERT INTO tableX(someInteger) VALUES .implode(',', $val)"; mysqli_query($con, $query); } $data = array(); for( $i =0; $i<99; $i++){ // Creating an array of data to be inserted. $data[ ] = '(" ' . $i. '")' ; } // Inserting the data in a single call insertValues( $data ); // Closing the connection as a best practice mysqli_close($con); ?> 

12. Frequently Used Switch Cases

Keep most frequently used switch cases on the top.

13. Use Methods in Derived Classes

Methods in derived classes are faster than base classes. For example, let there be a function in both base class and derived class for performing task1. It is named as “forTask1″ in base class and “forTask1again” in derived class, so that they will not override.

Call to the function “forTask1again( )” which is in derived class will work faster than call to the function “forTask1( )” as it is from base class.

 <?php class someBaseClass { public function forTask1($string) { // perform task 1 } public function forTask2( ) { // perform task 2 } } class derivedClass extends someBaseClass { public function forTask1again($string) { //perform task 1 same as the function in base class. } public function forTask3($string) { //perform task 3 } } //Instantiating the derived class below. $objDerivedClass = new derivedClass( ); // The call below works slow for task1 as it is from base class. $resultTask1 = $objDerivedClass->forTask1( ); // The call below works faster for task1 as // it is from derived class. $sameResultTask1 = $objDerivedClass->forTask1again(); ?> 

14. Use JSON

Use JSON instead of XML while working with web services as there are native php function like json_encode( ) and json_decode( ) which are very fast. If you are bound to have XML form of data, then use regular expression to parse it instead of DOM manipulation.

15. Use isset

Use isset( ) where ever possible instead of using count( ), strlen( ), sizeof( ) to check whether the value returned is greater than 0.

For example, let us assume that you have a function which returns an array with values or a NULL array. Now you want to check whether the returned array is with values or not, then use the following:

 if(isset($returnValue)){ // do something here } 

In this case, use the above code block, instead of the following:

 if(count($returnValue) > 0){ // do something here }
 

របៀប​ធ្វើ​ឲ្យ​យូនីកូដ​ខ្មែរ​បង្ហាញ​ត្ រូវ​នៅ​ក្នុង Adobe CS3/4

សរសេរ​ដោយ៖ អេង វណ្ណៈ

ទោះ​​បី​ជា​អក្សរ​ខ្មែរ​យូនីកូដ​ប្រភេទ​ថ្មី​ដែល​ចាប់ផ្ដើម​ដោយ Kh អាច​វាយ​បាន​នៅ​ក្នុង​កម្មវិធី​មួយ​ចំនួន​របស់ Adobe CS3 ក៏​ដោយ តែ​វា​នៅ​មាន​បញ្ហា​បន្តិច​បន្តួច ក្នុង​ការ​ដែល​ដៃ​ជើង និង​ស្រៈ​របស់​វា​មិន​ចូល​គ្នា ។ ដើម្បី​ដោះស្រាយ​បញ្ហា​នេះ​សូម​ធ្វើ​ដូច​ខាងក្រោម ៖

ចំពោះ Photoshop CS3 សូម​ជ្រើស Window -> Character -> ចុចទីនេះ ->OpenType ->Standard Ligatures

Illustrator CS3 សូម​ជ្រើស Window -> Type -> OpenType​ -> ចុចទីនេះ -> Standard Ligatures

Flash CS3 សូម​ជ្រើស Window -> Properties -> Character -> Anti-alias: Use Device Font…

ទាញ​​យក​ពុម្ព​អក្សរ Kh