<?xml version="1.0" encoding="UTF-8"?>
<feed version="0.3" xmlns="http://purl.org/atom/ns#" xml:lang="en-US">
	<title>Angel's Blog</title>
	<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php" />
	<modified>2026-05-13T17:36:18Z</modified>
	<author>
		<name>Angel</name>
	</author>
	<copyright>Copyright 2026, Angel</copyright>
	<generator url="http://www.sourceforge.net/projects/sphpblog" version="0.7.0">SPHPBLOG</generator>
	<entry>
		<title>MySQL Fun: Master-Slave Replication Example With Docker</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry190125-024233" />
		<content type="text/html" mode="escaped"><![CDATA[<pre># for historical purposes:<br />[acool@localhost ~]$ date<br />Thu Jan 24 18:44:23 PST 2019<br />[acool@localhost ~]$<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ cat /etc/redhat-release <br />Fedora release 28 (Twenty Eight)<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ sudo docker --version<br />Docker version 1.13.1, build 1556cce-unsupported<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ <br />[acool@localhost ~]$ sudo docker network create mysql-cluster<br />72af69d434e8cefa031555d2ba6039c2260aa73fe27df380b9454e3790c89337<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ <br />[acool@localhost ~]$ sudo docker network ls<br />NETWORK ID          NAME                DRIVER              SCOPE<br />5dfcb11eac94        bridge              bridge              local<br />c146b3afd86e        host                host                local<br />72af69d434e8        mysql-cluster       bridge              local<br />1299a7349094        none                null                local<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ <br />[acool@localhost ~]$ tree mysql-fun<br />mysql-fun<br />├── master<br />│   ├── config<br />│   │   └── mysqld.cnf<br />│   └── data<br />└── slave<br />    ├── config<br />    │   └── mysqld.cnf<br />    └── data<br /><br />6 directories, 2 files<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ cat mysql-fun/master/config/mysqld.cnf <br />[mysqld]<br />server_id = 1<br />log_bin = /var/log/mysql/mysql-bin-master<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ cat mysql-fun/slave/config/mysqld.cnf <br />[mysqld]<br />server_id = 2<br />relay_log = /var/log/mysql/mysql-relay-slave-bin<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ <br />[acool@localhost ~]$ getenforce<br />Permissive<br />[acool@localhost ~]$<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ sudo docker images<br />REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE<br />docker.io/mysql     5.7                 5cd9bd4c8a5e        3 days ago          372 MB<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ <br />[acool@localhost ~]$ sudo docker run -v /home/acool/mysql-fun/slave/config:/etc/mysql/conf.d -v /home/acool/mysql-fun/slave/data/:/var/lib/mysql/:rw --detach --network mysql-cluster --name=slave-mysql  --env=&quot;MYSQL_ROOT_PASSWORD=temp123&quot; mysql:5.7<br />599f302193cda964ada60d42e90324705c8d5b578c805c57f395958b97ed6702<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ <br />[acool@localhost ~]$ sudo docker run -v /home/acool/mysql-fun/master/config:/etc/mysql/conf.d -v /home/acool/mysql-fun/master/data/:/var/lib/mysql/:rw --detach --network mysql-cluster --name=master-mysql  --env=&quot;MYSQL_ROOT_PASSWORD=temp123&quot; mysql:5.7<br />32d0c2ecc7e6d17ae99ebabd6c75f0566846d60451bfb953b747b767dda92129<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ <br />[acool@localhost ~]$ sudo docker ps<br />CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES<br />32d0c2ecc7e6        mysql:5.7           &quot;docker-entrypoint...&quot;   15 seconds ago      Up 14 seconds       3306/tcp, 33060/tcp   master-mysql<br />599f302193cd        mysql:5.7           &quot;docker-entrypoint...&quot;   46 seconds ago      Up 44 seconds       3306/tcp, 33060/tcp   slave-mysql<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ <br />[acool@localhost ~]$ <br />[acool@localhost ~]$ sudo docker inspect master-mysql |grep \&quot;IPAddress\&quot;<br />            &quot;IPAddress&quot;: &quot;&quot;,<br />                    &quot;IPAddress&quot;: &quot;172.18.0.3&quot;,<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ sudo docker inspect slave-mysql |grep \&quot;IPAddress\&quot;<br />            &quot;IPAddress&quot;: &quot;&quot;,<br />                    &quot;IPAddress&quot;: &quot;172.18.0.2&quot;,<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ <br />[acool@localhost ~]$ <br />[acool@localhost ~]$ mysql -h 172.18.0.3 -u root -p<br />Enter password: <br />Welcome to the MySQL monitor.  Commands end with ; or \g.<br />Your MySQL connection id is 2<br />Server version: 5.7.25-log MySQL Community Server (GPL)<br /><br />Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.<br /><br />Oracle is a registered trademark of Oracle Corporation and/or its<br />affiliates. Other names may be trademarks of their respective<br />owners.<br /><br />Type &#039;help;&#039; or &#039;\h&#039; for help. Type &#039;\c&#039; to clear the current input statement.<br /><br />mysql&gt; <br />mysql&gt; CREATE USER &#039;replication_user&#039;@&#039;%&#039; IDENTIFIED BY &#039;ru_temp123&#039;;<br />Query OK, 0 rows affected (0.01 sec)<br /><br />mysql&gt; <br />mysql&gt; GRANT REPLICATION SLAVE ON *.* TO &#039;replication_user&#039;@&#039;%&#039;;<br />Query OK, 0 rows affected (0.01 sec)<br /><br />mysql&gt; FLUSH PRIVILEGES;<br />Query OK, 0 rows affected (0.01 sec)<br /><br />mysql&gt; SHOW MASTER STATUS;<br />+-------------------------+----------+--------------+------------------+-------------------+<br />| File                    | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |<br />+-------------------------+----------+--------------+------------------+-------------------+<br />| mysql-bin-master.000003 |      763 |              |                  |                   |<br />+-------------------------+----------+--------------+------------------+-------------------+<br />1 row in set (0.01 sec)<br /><br />mysql&gt; <br />mysql&gt; SHOW DATABASES;<br />+--------------------+<br />| Database           |<br />+--------------------+<br />| information_schema |<br />| mysql              |<br />| performance_schema |<br />| sys                |<br />+--------------------+<br />4 rows in set (0.00 sec)<br /><br />mysql&gt; exit<br />Bye<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ <br />[acool@localhost ~]$ <br />[acool@localhost ~]$ mysql -h 172.18.0.2 -p -u root <br />Enter password: <br />Welcome to the MySQL monitor.  Commands end with ; or \g.<br />Your MySQL connection id is 2<br />Server version: 5.7.25 MySQL Community Server (GPL)<br /><br />Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.<br /><br />Oracle is a registered trademark of Oracle Corporation and/or its<br />affiliates. Other names may be trademarks of their respective<br />owners.<br /><br />Type &#039;help;&#039; or &#039;\h&#039; for help. Type &#039;\c&#039; to clear the current input statement.<br /><br />mysql&gt; <br />mysql&gt; SELECT @@server_id;<br />+-------------+<br />| @@server_id |<br />+-------------+<br />|           2 |<br />+-------------+<br />1 row in set (0.00 sec)<br /><br />mysql&gt; CHANGE MASTER TO MASTER_HOST = &#039;172.18.0.3&#039;, MASTER_USER = &#039;replication_user&#039;, MASTER_PASSWORD = &#039;ru_temp123&#039;, MASTER_LOG_FILE = &#039;mysql-bin-master.000003&#039;, MASTER_LOG_POS = 763;<br />Query OK, 0 rows affected, 1 warning (0.10 sec)<br /><br />mysql&gt; START SLAVE;<br />Query OK, 0 rows affected (0.00 sec)<br /><br />mysql&gt; SHOW SLAVE STATUS\G;<br />*************************** 1. row ***************************<br />               Slave_IO_State: Waiting for master to send event<br />                  Master_Host: 172.18.0.3<br />                  Master_User: replication_user<br />                  Master_Port: 3306<br />                Connect_Retry: 60<br />              Master_Log_File: mysql-bin-master.000003<br />          Read_Master_Log_Pos: 763<br />               Relay_Log_File: mysql-relay-slave-bin.000002<br />                Relay_Log_Pos: 327<br />        Relay_Master_Log_File: mysql-bin-master.000003<br />             Slave_IO_Running: Yes<br />            Slave_SQL_Running: Yes<br />              Replicate_Do_DB: <br />          Replicate_Ignore_DB: <br />           Replicate_Do_Table: <br />       Replicate_Ignore_Table: <br />      Replicate_Wild_Do_Table: <br />  Replicate_Wild_Ignore_Table: <br />                   Last_Errno: 0<br />                   Last_Error: <br />                 Skip_Counter: 0<br />          Exec_Master_Log_Pos: 763<br />              Relay_Log_Space: 540<br />              Until_Condition: None<br />               Until_Log_File: <br />                Until_Log_Pos: 0<br />           Master_SSL_Allowed: No<br />           Master_SSL_CA_File: <br />           Master_SSL_CA_Path: <br />              Master_SSL_Cert: <br />            Master_SSL_Cipher: <br />               Master_SSL_Key: <br />        Seconds_Behind_Master: 0<br />Master_SSL_Verify_Server_Cert: No<br />                Last_IO_Errno: 0<br />                Last_IO_Error: <br />               Last_SQL_Errno: 0<br />               Last_SQL_Error: <br />  Replicate_Ignore_Server_Ids: <br />             Master_Server_Id: 1<br />                  Master_UUID: 60c1469e-2049-11e9-89ca-0242ac120003<br />             Master_Info_File: /var/lib/mysql/master.info<br />                    SQL_Delay: 0<br />          SQL_Remaining_Delay: NULL<br />      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates<br />           Master_Retry_Count: 86400<br />                  Master_Bind: <br />      Last_IO_Error_Timestamp: <br />     Last_SQL_Error_Timestamp: <br />               Master_SSL_Crl: <br />           Master_SSL_Crlpath: <br />           Retrieved_Gtid_Set: <br />            Executed_Gtid_Set: <br />                Auto_Position: 0<br />         Replicate_Rewrite_DB: <br />                 Channel_Name: <br />           Master_TLS_Version: <br />1 row in set (0.00 sec)<br /><br />ERROR: <br />No query specified<br /><br />mysql&gt; SHOW DATABASES;<br />+--------------------+<br />| Database           |<br />+--------------------+<br />| information_schema |<br />| mysql              |<br />| performance_schema |<br />| sys                |<br />+--------------------+<br />4 rows in set (0.00 sec)<br /><br />mysql&gt; exit<br />Bye<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ # create new database in master<br />[acool@localhost ~]$ mysql -h 172.18.0.3 -p -u root <br />Enter password: <br />Welcome to the MySQL monitor.  Commands end with ; or \g.<br />Your MySQL connection id is 4<br />Server version: 5.7.25-log MySQL Community Server (GPL)<br /><br />Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.<br /><br />Oracle is a registered trademark of Oracle Corporation and/or its<br />affiliates. Other names may be trademarks of their respective<br />owners.<br /><br />Type &#039;help;&#039; or &#039;\h&#039; for help. Type &#039;\c&#039; to clear the current input statement.<br /><br />mysql&gt; <br />mysql&gt; CREATE DATABASE users;<br />Query OK, 1 row affected (0.01 sec)<br /><br />mysql&gt; <br />mysql&gt; SHOW DATABASES;<br />+--------------------+<br />| Database           |<br />+--------------------+<br />| information_schema |<br />| mysql              |<br />| performance_schema |<br />| sys                |<br />| users              |<br />+--------------------+<br />5 rows in set (0.00 sec)<br /><br />mysql&gt; exit<br />Bye<br />[acool@localhost ~]$ # confirm database creation was replicated to slave<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ mysql -h 172.18.0.2 -p -u root <br />Enter password: <br />Welcome to the MySQL monitor.  Commands end with ; or \g.<br />Your MySQL connection id is 5<br />Server version: 5.7.25 MySQL Community Server (GPL)<br /><br />Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.<br /><br />Oracle is a registered trademark of Oracle Corporation and/or its<br />affiliates. Other names may be trademarks of their respective<br />owners.<br /><br />Type &#039;help;&#039; or &#039;\h&#039; for help. Type &#039;\c&#039; to clear the current input statement.<br /><br />mysql&gt; <br />mysql&gt; SHOW DATABASES;<br />+--------------------+<br />| Database           |<br />+--------------------+<br />| information_schema |<br />| mysql              |<br />| performance_schema |<br />| sys                |<br />| users              |<br />+--------------------+<br />5 rows in set (0.00 sec)<br /><br />mysql&gt; exit<br />Bye<br />[acool@localhost ~]$ <br />[acool@localhost ~]$ # Exercise finished! SQL statements are being replicated from master to slave :)<br />[acool@localhost ~]$ <br /></pre>]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry190125-024233</id>
		<issued>2019-01-25T00:00:00Z</issued>
		<modified>2019-01-25T00:00:00Z</modified>
	</entry>
	<entry>
		<title>MySQL: Loading a TSV file into a table.</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry150925-173422" />
		<content type="text/html" mode="escaped"><![CDATA[1.- The column names are in the first line, get them:<br /><pre>[aesteban@localhost BizEquityData]$ head -1 bizDataFile.tsv | tr &#039;\t&#039; &#039;\n&#039;<br />id<br />name<br />dbaname<br />address<br />city<br />state<br />postcode<br />latitude<br />longitude<br />phone<br />faxphone<br />contact<br />firstname<br />lastname<br />email<br />yearestablished<br />businessstatus<br />webaddress<br />corpemployees<br />localemployees<br />corpamount<br />localamount<br />localamount<br />stockexchangecode<br />stocktickersymbol<br />ceoname<br />cioname<br />cfoname<br />name<br />code<br /></pre><br />1a..- find out total lines in file:<br /><pre>[aesteban@localhost BizEquityData]$ cat bizDataFile.tsv | wc -l<br />1785338<br /></pre><br />2.- Create a table, rename any duplicate field names:<br /><pre>CREATE TABLE `bizDataTable` (<br />id                 varchar(255),<br />name               varchar(255),<br />dbaname            varchar(255),<br />address            varchar(255),<br />city               varchar(255),<br />state              varchar(255),<br />postcode           varchar(255),<br />latitude           varchar(255),<br />longitude          varchar(255),<br />phone              varchar(255),<br />faxphone           varchar(255),<br />contact            varchar(255),<br />firstname          varchar(255),<br />lastname           varchar(255),<br />email              varchar(255),<br />yearestablished    varchar(255),<br />businessstatus     varchar(255),<br />webaddress         varchar(255),<br />corpemployees      varchar(255),<br />localemployees     varchar(255),<br />corpamount         varchar(255),<br />localamount        varchar(255),<br />localamount2        varchar(255),<br />stockexchangecode  varchar(255),<br />stocktickersymbol  varchar(255),<br />ceoname            varchar(255),<br />cioname            varchar(255),<br />cfoname            varchar(255),<br />name2               varchar(255),<br />code               varchar(255)<br />) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre><br />3.- Connect to the server and load the local file:<br /><pre>[aesteban@localhost BizEquityData]$ mysql -u USERNAME -h dev.example.com -p --local-infile bizDataDB<br />MySQL [bizDataDB]&gt; load data local infile &#039;/home/aesteban/Documents/BizEquityData/bizDataFile.tsv&#039; into table bizDataTable fields terminated by &#039;\t&#039; lines terminated by &#039;\n&#039; ignore 1 lines;<br /><br />MySQL [bizData]&gt; select count(*)  from bizDataTable;<br />+----------+<br />| count(*) |<br />+----------+<br />|  1785337 |<br />+----------+<br />1 row in set (0.00 sec)<br /></pre><br /><br />Enjoy!!<br /><br />BONUS: Dump select statement locally as a TSV file:<br /><pre>[aesteban@localhost FilteredReports]$ mysql -u USERNAME -h dev.example.com -p bizDataDB -e &quot;select * from bizDataTable where email != &#039;NULL&#039;&quot; &gt; bizData_email.tsv<br /></pre><br /><br />If it&#039;s a CSV file, some fields may contain a comma, try something like the following:<br /><pre>MySQL [jupiter]&gt; load data local infile &#039;e360Data.csv&#039; into table e360MasterOnline fields optionally enclosed by &#039;&quot;&#039; terminated by &#039;,&#039; lines terminated by &#039;\n&#039; ignore 1 lines;</pre><br />]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry150925-173422</id>
		<issued>2015-09-25T00:00:00Z</issued>
		<modified>2015-09-25T00:00:00Z</modified>
	</entry>
	<entry>
		<title>MySQL – Generating Row Number for Each Row Using Variables in Query. (Ranking query results)</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry140702-151054" />
		<content type="text/html" mode="escaped"><![CDATA[Ranking field for result sets.<br /><br />MySQL does not have any system function like SQL Server’s row_number () to generate the row number for each row. However, it can be generated using the variable in the SELECT statement.<br /><br />The following table has five rows.<br /><pre><br />CREATE TABLE mysql_testing(db_names VARCHAR(100));<br />INSERT INTO mysql_testing<br />SELECT &#039;SQL Server&#039; UNION ALL<br />SELECT &#039;MySQL&#039; UNION ALL<br />SELECT &#039;Oracle&#039; UNION ALL<br />SELECT &#039;MongoDB&#039; UNION ALL<br />SELECT &#039;PostGreSQL&#039;;</pre><br /><br />Now you can generate the row number using a variable in two methods<br /><br />Method 1 : Set a variable and use it in a SELECT statement<br /><pre>SET @row_number:=0;<br />SELECT @row_number:=@row_number+1 AS row_number,db_names FROM mysql_testing<br />ORDER BY db_names;</pre><br /><br />Method 2 : Use a variable as a table and cross join it with the source table<br /><br /><pre>SELECT @row_number:=@row_number+1 AS rank,db_names FROM mysql_testing,<br />(SELECT @row_number:=0) AS t <br />ORDER BY db_names;</pre><br /><br />Both the above methods return the following result<br /><br />row_number db_names<br /> 1 MongoDB<br /> 2 MySQL<br /> 3 Oracle<br /> 4 PostGreSQL<br /> 5 SQL Server<br /><br />//source (as of 6-2-2014)<br /><a href="http://blog.sqlauthority.com/2014/03/08/mysql-generating-row-number-for-each-row-using-variable/" >http://blog.sqlauthority.com/2014/03/08 ... -variable/</a><br /><br />//my 2 cents -ac<br /><pre>select @rn := @rn+1 AS RANK,t1.* from (<br /><br /> select * from Franchises limit 500<br /><br />) t1, (SELECT @rn:=0) t2;&quot;;<br /><br /><br /></pre>]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry140702-151054</id>
		<issued>2014-07-02T00:00:00Z</issued>
		<modified>2014-07-02T00:00:00Z</modified>
	</entry>
	<entry>
		<title>MySQL SSL Setup</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry140511-164525" />
		<content type="text/html" mode="escaped"><![CDATA[//Server and client &quot;Common Name&quot; in certificates must be different than CA&#039;s :<br /><a href="http://stackoverflow.com/questions/20459056/mysql-and-ssl-connection-failing-error-2026-hy000/23599624#23599624" >http://stackoverflow.com/questions/2045 ... 4#23599624</a><br /><br />1.- generate CA key and certificate(2 commands create 2 files)<br /><pre>openssl genrsa 2048 &gt;ca.key //creates ca.key<br />openssl req -new -x509 -nodes -days 3600 -key &#039;ca.key&#039; &gt; &#039;ca.crt&#039; //creates certificate</pre><br /><br />2.- generate server key and signed certificate(2 commands create 3 files)<br /><pre>openssl req -newkey rsa:2048 -days 3600 -nodes -keyout &#039;server.key&#039; &gt; server.csr&#039; //create key and csr<br />openssl x509 -req -in &#039;server.csr&#039; -days 3600 -CA &#039;ca.crt&#039; -CAkey &#039;ca.key&#039; -set_serial 01 &gt; &#039;server.crt&#039; //creates certificate</pre><br /><br />3.- generate client key and certificate (2 commands create 3 files)<br /><pre>openssl req -newkey rsa:2048 -days 3600 -nodes -keyout &#039;client.key&#039; &gt; &#039;client.csr&#039; //creates key and csr<br />openssl x509 -req -in &#039;client.csr&#039; -days 3600 -CA &#039;ca.crt&#039; -CAkey &#039;ca.key&#039; -set_serial 01 &gt; &#039;client.crt&#039;</pre><br /><br />4.- create SSL user:<br /><pre>GRANT ALL PRIVILEGES ON *.* TO &#039;ssluser&#039;@&#039;%&#039; IDENTIFIED BY &#039;secret-passwd&#039; REQUIRE SSL;</pre><br /><br />5.- update my.cnf<br /><pre><br />[mysqld]<br />ssl-ca		= &quot;ca.crt&quot;<br />ssl-cert	= &quot;server.crt&quot;<br />ssl-key		= &quot;server.key&quot;<br /><br />[client]<br />ssl-ca=ca.crt<br />ssl-cert=client.crt<br />ssl-key=client.key</pre><br /><br /><br />//MySQL workbench, use: ca.key, client.crt and client.key without password:<br /><pre>openssl rsa -in client.key -out client-nopasswd.key</pre> ]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry140511-164525</id>
		<issued>2014-05-11T00:00:00Z</issued>
		<modified>2014-05-11T00:00:00Z</modified>
	</entry>
	<entry>
		<title>MySQL Backups</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry140124-171833" />
		<content type="text/html" mode="escaped"><![CDATA[<pre>//dump a database<br />mysqldump -u UserName -p --host=dev.barney.com db_name &gt; db_name_backup.sql<br />//compressed dump<br />mysqldump -u UserName -p --host=dev.barney.com db_name | gzip &gt; db_name_backup.sql<br /><br /><br />//restore database<br />mysql -u UserName -p  target_db_name &lt; db_name_backup.sql<br /><br />//dump and restore <br />mysqldump -u UserName -p --host=dev.barney.com db_name | mysql -u UserName -p target_db_name <br /><br /></pre>]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry140124-171833</id>
		<issued>2014-01-25T00:00:00Z</issued>
		<modified>2014-01-25T00:00:00Z</modified>
	</entry>
	<entry>
		<title>MySQL: Search and replace a string in a column.</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry131001-140117" />
		<content type="text/html" mode="escaped"><![CDATA[MySQL database has a handy and simple string function REPLACE() that allows table data with the matching string (from_string) to be replaced by new string (to_string). This is useful if there is need to search and replace a text string which affects many records or rows, such as change of company name, postcode, URL or spelling mistake.<br /><br />The syntax of REPLACE is REPLACE(text_string, from_string, to_string)<br /><br />MySQL reference describes REPLACE as function that returns the string text_string with all occurrences of the string from_string replaced by the string to_string, where matching is case-sensitive when searching for from_string. text_string can be retrieved from the a field in the database table too. Most SQL command can be REPLACE() function, especially SELECT and UPDATE manipulation statement.<br /><br />For example:<br /><pre>update TABLE_NAME set FIELD_NAME = replace(FIELD_NAME, ‘find this string’, ‘replace found string with this string’);<br /><br />update client_table set company_name = replace(company_name, ‘Old Company’, ‘New Company’)</pre><br /><br />The above statement will replace all instances of ‘Old Company’ to ‘New Company’ in the field of company_name of client_table table.<br /><br />Another example:<br /><br /><pre>SELECT REPLACE(‘www.mysql.com’, ‘w’, ‘Ww’);</pre><br /><br />Above statement will return ‘WwWwWw.mysql.com’ as result.<br /><br /><a href="http://www.mydigitallife.info/how-to-find-and-replace-text-in-mysql-database-using-sql/" >http://www.mydigitallife.info/how-to-fi ... using-sql/</a>]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry131001-140117</id>
		<issued>2013-10-01T00:00:00Z</issued>
		<modified>2013-10-01T00:00:00Z</modified>
	</entry>
	<entry>
		<title>Dropping, Adding or Repositioning a Column (ALTER command)</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry130930-114433" />
		<content type="text/html" mode="escaped"><![CDATA[<p>
Suppose you want to drop an existing column <b>i</b> from above MySQL table then you will use <b>DROP</b> clause along with <b>ALTER</b> command as follows:</p>
<pre class="prettyprint">
mysql> ALTER TABLE testalter_tbl  DROP i;
</pre>
<p>A <b>DROP</b> will not work if the column is the only one left in the table.</p>
<p>To add a column, use ADD and specify the column definition. The following statement restores the <b>i</b> column to testalter_tbl:</p>
<pre class="prettyprint">
mysql> ALTER TABLE testalter_tbl ADD i INT;
</pre>
<p>After issuing this statement, testalter will contain the same two columns that it had when you first created the table, but will not have quite the same structure. That's because new columns are added to the end of the table by default. So even though <b>i</b> originally was the first column in mytbl, now it is the last one.</p>
<pre class="prettyprint">
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| c     | char(1) | YES  |     | NULL    |       |
| i     | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
</pre>
<p>To indicate that you want a column at a specific position within the table, either use FIRST to make it the first column or AFTER col_name to indicate that the new column should be placed after col_name. Try the following ALTER TABLE statements, using SHOW COLUMNS after each one to see what effect each one has:</p>
<pre class="prettyprint">
ALTER TABLE testalter_tbl DROP i;
ALTER TABLE testalter_tbl ADD i INT FIRST;
ALTER TABLE testalter_tbl DROP i;
ALTER TABLE testalter_tbl ADD i INT AFTER c;
</pre>
<p>The FIRST and AFTER specifiers work only with the ADD clause. This means that if you want to reposition an existing column within a table, you first must DROP it and then ADD it at the new position.

</p><br /><br />:)<br /><br /><a href="http://www.tutorialspoint.com/mysql/mysql-alter-command.htm" >http://www.tutorialspoint.com/mysql/mys ... ommand.htm</a>]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry130930-114433</id>
		<issued>2013-09-30T00:00:00Z</issued>
		<modified>2013-09-30T00:00:00Z</modified>
	</entry>
	<entry>
		<title>MySQL: CAST example</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry130923-133717" />
		<content type="text/html" mode="escaped"><![CDATA[<pre>SELECT <br />    CAST(CASE eoy<br />        WHEN 0 THEN &#039;No Voted&#039; <br />         ELSE category/* Keep Original Value*/<br />    END as CHAR) AS Result<br />FROM `vote_email`</pre><br /><br />//see all<br /><pre>SELECT eoy FROM vote_email</pre>]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry130923-133717</id>
		<issued>2013-09-23T00:00:00Z</issued>
		<modified>2013-09-23T00:00:00Z</modified>
	</entry>
	<entry>
		<title>MySQL: Case Expression vs Case Statement</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry130923-114853" />
		<content type="text/html" mode="escaped"><![CDATA[The CASE expression evaluates to a value, i.e. it is used to evaluate to one of a set of results, based on some condition.<br />Example:<br /><br /><pre>SELECT CASE<br />    WHEN type = 1 THEN &#039;foo&#039;<br />    WHEN type = 2 THEN &#039;bar&#039;<br />    ELSE &#039;baz&#039;<br />END AS name_for_numeric_type<br />FROM sometable`</pre><br /><br />The CASE statement executes one of a set of statements, based on some condition.<br />Example:<br /><br /><pre>CASE<br />    WHEN action = &#039;update&#039; THEN<br />        UPDATE sometable SET column = value WHERE condition;<br />    WHEN action = &#039;create&#039; THEN<br />        INSERT INTO sometable (column) VALUES (value);<br />END CASE</pre><br /><br />You see how they are similar, but the statement does not evaluate to a value and can be used on its own, while the expression needs to be a part of an expression, e.g. a query or an assignment. You cannot use the statement in a query, since a query cannot contain statements, only expressions that need to evaluate to something (the query itself is a statement, in a way), e.g. SELECT CASE WHEN condition THEN UPDATE table SET something; END CASE makes no sense.<br /><br /><a href="http://stackoverflow.com/questions/12436859/case-expression-vs-case-statement" >http://stackoverflow.com/questions/1243 ... -statement</a>]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry130923-114853</id>
		<issued>2013-09-23T00:00:00Z</issued>
		<modified>2013-09-23T00:00:00Z</modified>
	</entry>
	<entry>
		<title>MySQL: User Management</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry130916-203117" />
		<content type="text/html" mode="escaped"><![CDATA[// view all users<br /><pre>SELECT user,host FROM mysql.user;</pre><br />//drop a user<br /><pre>DROP USER &#039;dev-webuser&#039;@&#039;localhost&#039;;</pre><br />//create a user and assign password <br /><pre>GRANT ALL PRIVILEGES ON db_name.* TO &#039;webuser&#039;@&#039;localhost&#039; IDENTIFIED BY &#039;secret123&#039;</pre><br />// disply logged in grants<br /><pre>SHOW GRANTS;</pre><br /><br /><br />//<br />CREATE USER &#039;jeffrey&#039;@&#039;localhost&#039; IDENTIFIED BY &#039;mypass&#039;;<br /><br />//<br />GRANT SELECT,INSERT,UPDATE,DELETE ON my_db.* TO &#039;michael&#039;@&#039;localhost&#039;;<br /><br />//<br />GRANT ALL ON my_db.* TO &#039;michael&#039;@&#039;localhost&#039;;<br /><br />//<br />GRANT ALL ON my_db.* TO &#039;my_user&#039;@localhost IDENTIFIED BY &#039;my_pass&#039;;<br /><br /><br />//update user&#039;s password:<br />SET PASSWORD FOR &#039;webuser&#039;@&#039;localhost&#039; = PASSWORD(&#039;dev123&#039;);<br /><br />// MySQL 8 :<br /><pre>root@5f288b2166ba:/# mysql -p<br />...<br />mysql&gt; <br />mysql&gt; CREATE USER &#039;coolUser&#039;@&#039;%&#039; IDENTIFIED WITH mysql_native_password BY &#039;YYYYYY&#039;;<br />Query OK, 0 rows affected (0.01 sec)<br /><br />mysql&gt; <br />mysql&gt; grant all on *.* to &#039;coolUser&#039;@&#039;%&#039;;<br />Query OK, 0 rows affected (0.01 sec)<br /><br />#Starting with MySQL 8 you no longer can (implicitly) create a user using the GRANT command. Use CREATE USER instead, followed by the GRANT statement:<br />mysql&gt; CREATE USER &#039;root&#039;@&#039;%&#039; IDENTIFIED BY &#039;PASSWORD&#039;;<br />mysql&gt; GRANT ALL PRIVILEGES ON *.* TO &#039;root&#039;@&#039;%&#039; WITH GRANT OPTION;<br />mysql&gt; FLUSH PRIVILEGES;<br /></pre>]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry130916-203117</id>
		<issued>2013-09-16T00:00:00Z</issued>
		<modified>2013-09-16T00:00:00Z</modified>
	</entry>
	<entry>
		<title>Counting Table Columns</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry130809-155316" />
		<content type="text/html" mode="escaped"><![CDATA[SELECT COUNT(*)<br />FROM INFORMATION_SCHEMA.COLUMNS<br />WHERE table_schema = &#039;database_name&#039;<br />  AND table_name = &#039;table_name&#039;]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry130809-155316</id>
		<issued>2013-08-09T00:00:00Z</issued>
		<modified>2013-08-09T00:00:00Z</modified>
	</entry>
	<entry>
		<title>Selecting Random Rows in MySQL</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry130620-222833" />
		<content type="text/html" mode="escaped"><![CDATA[SELECT * FROM tablename<br />        WHERE somefield=&#039;something&#039;<br />        ORDER BY RAND() LIMIT 5<br />]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry130620-222833</id>
		<issued>2013-06-21T00:00:00Z</issued>
		<modified>2013-06-21T00:00:00Z</modified>
	</entry>
	<entry>
		<title>Populating a Table from another Table</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry130620-195532" />
		<content type="text/html" mode="escaped"><![CDATA[INSERT INTO NewTable (col1, col2, col3) SELECT col1, col2, col3 FROM OldTable<br /><br />Page 985 in MySQL Developer&#039;s Library (Paul DuBois), and<br /><a href="http://stackoverflow.com/questions/3140770/populate-table-from-one-to-another" >http://stackoverflow.com/questions/3140 ... to-another</a>]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry130620-195532</id>
		<issued>2013-06-21T00:00:00Z</issued>
		<modified>2013-06-21T00:00:00Z</modified>
	</entry>
	<entry>
		<title>How to part DATE and TIME from DATETIME field type in MySQL?</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry130610-075808" />
		<content type="text/html" mode="escaped"><![CDATA[//Use the following query:<br />SELECT DATE(`date_time_field`) AS date_part, TIME(`date_time_field`) AS time_part FROM `your_table`;<br /><br />//Also you can use:<br />SELECT DATE_FORMAT(colName,&#039;%Y-%m-%d&#039;) DATEONLY,DATE_FORMAT(colName,&#039;%H:%i:%s&#039;) TIMEONLY FROM `your_table`;<br /><br /><a href="http://stackoverflow.com/questions/12337195/how-to-part-date-and-time-from-datetime-in-mysql" >http://stackoverflow.com/questions/1233 ... e-in-mysql</a>]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry130610-075808</id>
		<issued>2013-06-10T00:00:00Z</issued>
		<modified>2013-06-10T00:00:00Z</modified>
	</entry>
	<entry>
		<title>MySQL/Language/Definitions: what are DDL, DML and DQL?</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry130514-194210" />
		<content type="text/html" mode="escaped"><![CDATA[<br />    --DDL (Data Definition Language) refers to the CREATE, ALTER and DROP statements<br /><br />DDL allows to add / modify / delete the logical structures which contain the data or which allow users to access / mantain the data (databases, tables, keys, views...). DDL is about &quot;metadata&quot;.<br /><br />    --DML (Data Manipulation Language) refers to the INSERT, UPDATE and DELETE statements<br /><br />DML allows to add / modify / delete data itself.<br /><br />    --DQL (Data Query Language) refers to the SELECT, SHOW and HELP statements (queries)<br /><br />SELECT is the main DQL instruction. It retrieves data you need. SHOW retrieves infos about the metadata. HELP... is for people who need help.<br /><br />    --DCL (Data Control Language) refers to the GRANT and REVOKE statements<br /><br />DCL is used to grant / revoke permissions on databases and their contents. DCL is simple, but MySQL&#039;s permissions are rather complex. DCL is about security.<br /><br />    --DTL (Data Transaction Language) refers to the START TRANSACTION, SAVEPOINT, COMMIT and ROLLBACK [TO SAVEPOINT] statements<br /><br />DTL is used to manage transactions (operations which include more instructions none of which can be executed if one of them fails).]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry130514-194210</id>
		<issued>2013-05-15T00:00:00Z</issued>
		<modified>2013-05-15T00:00:00Z</modified>
	</entry>
	<entry>
		<title>Preventing  SQL Injection and Cross-Site Scripting (XSS)</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry130326-104808" />
		<content type="text/html" mode="escaped"><![CDATA[It&#039;s a common misconception that user input can be filtered. PHP even has a (now deprecated) &quot;feature&quot;, called magic-quotes, that builds on this idea. It&#039;s nonsense. Forget about filtering (Or cleaning, or whatever people call it).<br /><br />What you should do, to avoid problems is quite simple: Whenever you embed a string within foreign code, you must escape it, according to the rules of that language. For example, if you embed a string in some SQL targeting MySql, you must escape the string with MySql&#039;s function for this purpose (mysql_real_escape_string).<br /><br />Another example is HTML; If you embed strings within HTML markup, you must escape it with htmlspecialchars. This means that every single echo or print statement should use htmlspecialchars.<br /><br />A third example could be shell commands; If you are going to embed strings (Such as arguments) to external commands, and call them with exec, then you must use escapeshellcmd and escapeshellarg.<br /><br />And so on and so forth ...<br /><br />The only case where you need to actively filter data, is if you&#039;re accepting preformatted input. Eg. if you let your users post HTML markup, that you plan to display on the site. However, you should be wise to avoid this at all cost, since no matter how well you filter it, it will always be a potential security hole.<br /><br /><a href="http://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php" >http://stackoverflow.com/questions/1296 ... t-with-php</a><br />]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry130326-104808</id>
		<issued>2013-03-26T00:00:00Z</issued>
		<modified>2013-03-26T00:00:00Z</modified>
	</entry>
	<entry>
		<title>Code to populate mysql with random data (needs some cleaning)</title>
		<link rel="alternate" type="text/html" href="https://angelcool.net/sphpblog/blog_index.php?entry=entry120820-073441" />
		<content type="text/html" mode="escaped"><![CDATA[CREATE TABLE `RandomNumbers_InnoDB` (<br />   `id` int(11) NOT NULL auto_increment,<br />   `random1` varchar(100) default NULL,<br />   `random2` varchar(100) default NULL,<br />   `random3` varchar(100) default NULL,<br />   PRIMARY KEY  (`id`)<br /> ) ENGINE=InnoDB DEFAULT CHARSET=latin1<br /><br />Sample ouput:<br /><a href="http://www.angelcool.net/tutorials/other/TestResult_2500rows.txt" >http://www.angelcool.net/tutorials/othe ... 00rows.txt</a><br /><br /><pre><br />&lt;?php<br />set_time_limit(0);<br /><br />function db_link()<br />{<br /><br /><br /><br /><br />//@ suppresses the error mysqli_connect returns, and instead we use our die() error<br />$db_link=mysqli_connect(&#039;127.0.0.1&#039;,&#039;root&#039;,&#039;&#039;);<br /><br /><br /><br /><br />if($db_link==false)<br />echo &#039;Could NOT connect to MySQL, check mysqli_connect settings. &#039;;<br /><br /><br />//select database<br />if(@mysqli_select_db($db_link,&#039;test&#039;)==false)<br />echo &#039;Could NOT select DB, check DB name.&#039;;<br /><br /><br />return $db_link;<br /><br />}<br /><br /><br /><br />function String()<br />{<br />			 //Step 1 Generate a token.<br />			$length = 32; <br />			$chars =  &#039;ABCDEFGHIJKLMNPQRSTUVWXYZ123456789&#039;; //ABCDEFGHIJKLMNPQRTWXYZ123456789    123456789abcdefghijklmnopqrstwxzABCDEFGHIJKLMNPQRTWXYZ<br />			$string = &#039;&#039;; <br />			for ($i = 0; $i &lt; $length; $i++) { <br />				$pos = rand(0, strlen($chars)-1); <br />				$string .= $chars{$pos}; }<br />	<br />	return $string;<br />	<br />}<br /><br /><br /><br />		<br />		/*<br />		How many different 4-letter combinations are there in the alphabet?<br />		letters in alphabet = 26<br />		<br />		Answer:<br />		26^4 = 456,976<br />		There are 26 choices for the first letter, 26 for the second, 26 for the 3rd and 26 for the 4th. So altogether, there are 26*26*26*26 = 456,976 combinations.<br /><br />		I hope this helps!<br />		<br />		<a href="http://answers.yahoo.com/question/index?qid=20080603161851AAkpgEj" >http://answers.yahoo.com/question/index ... 851AAkpgEj</a><br />		*/<br />	<br />		$conn=db_link();<br />		echo &#039;&lt;b&gt;&#039;.date(DATE_RFC822).&#039;&lt;/b&gt;&#039;;<br />		<br />		$execution_time=microtime(true);	<br />	<br />		for($iii=1;$iii&lt;=200;)<br />		{<br />			$start=microtime(true);<br />		<br /><br />		<br />		/*<br />		<br />		//Run this query to find out duplicate tokens<br />		SELECT * FROM BulkTokens INNER JOIN (SELECT Token,COUNT(Token) AS Duplicated FROM BulkTokens <br />				     GROUP BY Token HAVING Duplicated &gt; 1) dup ON BulkTokens.Token=dup.Token;<br /><br />				<br />		*/<br />		<br />		$string1=String(); $string2=String(); $string3=String();<br />		<br />				//Step 2 Check if token DOES NOT exist in database (check if it is duplicated, if it is skip this iteration).<br />			//	$query=&quot;SELECT random1 FROM RandomNumbers_InnoDB WHERE BINARY random1=&#039;&quot;.$string1.&quot;&#039; and random2=&#039;&quot;.$string2.&quot;&#039; and random3=&#039;&quot;.$string3.&quot;&#039;&quot;;<br />			//	$result=mysqli_query($conn,$query) or die(mysqli_error($conn));<br />			//	$query=mysqli_num_rows($result);<br /><br />				<br />				<br />				//if token exists skip iteration.mysqli_num_rows($query)==0<br />				if(true)//$query==0<br />				{<br />							<br />				//If token does not exist add 1 to $iii and assign the token to array.	<br />				<br />				<br /><br />				// and insert it in database.<br />				$query=&quot;INSERT INTO RandomNumbers_InnoDB(random1,random2,random3) VALUES(&#039;&quot;.$string1.&quot;&#039;,&#039;&quot;.$string2.&quot;&#039;,&#039;&quot;.$string3.&quot;&#039;);&quot;;<br />				mysqli_query($conn,$query) or die(mysqli_error($conn));<br />				echo $iii.&#039;----&#039;.$string1.&#039;----&#039;.$string2.&#039;----&#039;.$string3.&#039;          Iteration execution time:&#039;.round((microtime(true)-$start),4).&#039; secs&lt;br&gt;&#039;;<br />				$iii++;<br />					<br />				}<br />				else<br />				{ echo &#039;====================================================================================================SKIPPED REPEATED RECORD !!&#039;;}<br /><br /><br /><br />		}<br />		echo &#039;&lt;br&gt;&lt;br&gt;&lt;br&gt;Total Execution Time:&#039;.round((microtime(true)-$execution_time),4).&#039;&lt;br&gt;&lt;br&gt;&lt;br&gt;&#039;;<br />		<br />		echo &#039;&lt;b&gt;&#039;.date(DATE_RFC822).&#039;&lt;/b&gt;&#039;;<br />        <br />        ?&gt;<br /></pre>]]></content>
		<id>https://angelcool.net/sphpblog/blog_index.php?entry=entry120820-073441</id>
		<issued>2012-08-20T00:00:00Z</issued>
		<modified>2012-08-20T00:00:00Z</modified>
	</entry>
</feed>
