Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!
DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
  • submit to reddit

MySQL Snippets

  • php
  • MySQL
  • SQL
  • Array
  • Database
                    Absurdly simple but utilitarian function returns a numeric array of associative arrays containing an entire result set.

<code>function mysql_fetch_all($result) {
    $all = array();
    while ($all[] = mysql_fetch_assoc($result)) {}
    return $all;
}</code>                
  • Database
  • php
  • MySQL
  • SQL
  • Array
                    Absurdly simple but utilitarian function returns a numeric array of associative arrays containing an entire result set.

<code>function mysql_fetch_all($result) {
    $all = array();
    while ($all[] = mysql_fetch_assoc($result)) {}
    return $all;
}</code>                
  • Row
  • Fast
  • directory
  • php
  • MySQL
                    PHP MySQL Select Row Randomly Fast

<code>
<?php

  //CODE FROM WWW.GREGGDEV.COM

  function random_row($table, $column) {

      $max_sql = "SELECT max(" . $column . ") 

                  AS max_id

                  FROM " . $table;

      $max_row = mysql_fetch_array(mysql_query($max_sql));

      $random_number = mt_rand(1, $max_row['max_id']);

      $random_sql = "SELECT * FROM " . $table . "

                     WHERE " . $column . " >= " . $random_number . " 

                     ORDER BY " . $column . " ASC

                     LIMIT 1";

      $random_row = mysql_fetch_row(mysql_query($random_sql));

      if (!is_array($random_row)) {

          $random_sql = "SELECT * FROM " . $table . "

                         WHERE " . $column . " < " . $random_number . " 

                         ORDER BY " . $column . " DESC

                         LIMIT 1";

          $random_row = mysql_fetch_row(mysql_query($random_sql));

      }

      return $random_row;

  }

  

  //USAGE

  echo '<pre>';

  print_r(random_row('YOUR_TABLE', 'YOUR_COLUMN'));

  echo '</pre>';

?>
</code>

Credits: <strong><a href='http://4dlink.com'>4dlink web lists</a></strong> and <a href='http://web4link.com'>web4link.com</a>                
  • MySQL
                    // change definer and triggers to 'root'@'localhost'

<code>
#!/bin/sh
host='localhost'
user='root'
port='3306'
# following should be the root@localhost password
password='root@123'

# triggers backup
mysqldump -h$host -u$user -p$password -P$port --all-databases -d --no-create-info > triggers.sql
if [[ $? -ne 0 ]]; then exit 81; fi

# stored procedure backup
mysqldump -h$host -u$user -p$password -P$port --all-databases --no-create-info --no-data -R --skip-triggers > procedures.sql
if [[ $? -ne 0 ]]; then exit 91; fi

# triggers backup
mysqldump -h$host -u$user -p$password -P$port --all-databases -d --no-create-info | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
if [[ $? -ne 0 ]]; then exit 101; fi

# drop current triggers
mysql -h$host -u$user -p$password -P$port -Bse"select CONCAT('drop trigger ', TRIGGER_SCHEMA, '.', TRIGGER_NAME, ';') from information_schema.triggers" | mysql -h$host -u$user -p$password -P$port
if [[ $? -ne 0 ]]; then exit 111; fi

# Restore from file, use root@localhost credentials
mysql -h$host -u$user -p$password -P$port < triggers_backup.sql
if [[ $? -ne 0 ]]; then exit 121; fi

# change all the definers of stored procedures to root@localhost
mysqldump -h$host -u$user -p$password -P$port --all-databases --no-create-info --no-data -R --skip-triggers | sed -e 's/DEFINER=[^*]*\*/\*/' | mysql -h$host -u$user -p$password -P$port
if [[ $? -ne 0 ]]; then exit 131; fi

</code>
                
  • php
  • MySQL
  • SQL
  • Rails
  • Ruby
                    //demonstra com seleccionar todos os aniversários que ocorrerão de hoje a 15 dias
//faça cache deste dados

<code>
SELECT SQL_CACHE /*??? prefira memcache, APC, etc..*/
  name,
  birthday,
  YEAR(birthday),
  YEAR(NOW()),
  (YEAR(NOW()) - YEAR(birthday)),
  DATE_ADD(birthday, INTERVAL (YEAR(NOW()) - YEAR(birthday)) YEAR),
  DATE_ADD(NOW(), INTERVAL 15 DAY )

FROM customers

WHERE

DATE_ADD(birthday, INTERVAL (YEAR(NOW()) - YEAR(birthday)) YEAR) 
  BETWEEN 
    DATE( NOW() )
  AND 
    DATE_ADD(NOW(), INTERVAL 15 DAY )
</code>                
  • MySQL
                    // install and start mysql proxy that will log failed queries

<code>


#!/bin/sh
# kill the current proxy if any
ps aux | grep "mysql-proxy" | awk '{print "kill -9 ", $2}' | sh

# download and install
cd /usr/share/mysql/ && wget http://mysql.oss.eznetsols.org/Downloads/MySQL-Proxy/mysql-proxy-0.8.1-linux-rhel5-x86-64bit.tar.gz
tar -xvf mysql-proxy-0.8.1-linux-rhel5-x86-64bit.tar.gz

# create an alias
alias myproxy='sh /usr/share/mysql/mysql-proxy-0.8.1-linux-rhel5-x86-64bit/bin/mysql-proxy --plugins=proxy --proxy-lua-script=/usr/share/mysql/mysql-proxy-0.8.1-linux-rhel5-x86-64bit/share/doc/mysql-proxy/failed-query.lua >> /home/failed_query.log &'

# failed query script
cat > /usr/share/mysql/mysql-proxy-0.8.1-linux-rhel5-x86-64bit/share/doc/mysql-proxy/failed-query.lua << "my_here_doc"

 local log_file = '/home/mysql.log'
 local fh = io.open(log_file, "a+")

function read_query(packet)
if string.byte(packet) == proxy.COM_QUERY then
query = string.sub(packet, 2)
proxy.queries:append(1, packet, {resultset_is_needed = true} )
return proxy.PROXY_SEND_QUERY
end
end

function read_query_result (inj)
local res = assert(inj.resultset)

-- if res.query_status == proxy.MYSQLD_PACKET_ERR then

if (res.query_status == proxy.MYSQLD_PACKET_ERR) or (res.warning_count > 0) then

local query = string.sub(inj.query, 2)
local err_code     = res.raw:byte(2) + (res.raw:byte(3) * 256)
local err_sqlstate = res.raw:sub(5, 9)
local err_msg      = res.raw:sub(10)

fh:write(string.sub(inj.query, 2), "\n")
fh:write(res.raw:sub(10), "\n")
fh:flush()

print("Query Received -", query)
print("Query Error code -", err_code)
print("Query Error Sqlstate -", err_sqlstate)
print("Query Error message -", err_msg)
print("Query warnings -", res.warning_count)

end
end

my_here_doc

</code>                
  • shell_script
  • MySQL
  • forge
  • oksoft
                    // create to_days(first_day), to_days(second_day) syntax that can be directly used while creating partitions based on month.


Create a table in the test database with the name "date_helper"

mysql> CREATE TABLE test.date_helper (
    id INT NOT NULL,
    to_timestamp datetime
);

Run the shell script and feed the output to mysql

unix> sh mydate.sh | mysql -uUser -pPassWd test

_____

The altered table will look something like this:

CREATE TABLE `date_helper` (
  `id` int(11) NOT NULL,
  `to_timestamp` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
/*!50100 PARTITION BY LIST (to_days(to_timestamp))
(PARTITION January2010 VALUES IN (734138,734139,734140, ...) ENGINE = InnoDB,
 PARTITION February2010 VALUES IN (734169,734170,734171,... ) ENGINE = InnoDB,
...
...
PARTITION November2011 VALUES IN (734807,734808,734809,...) ENGINE = InnoDB,
PARTITION December2011 VALUES IN (734837,734838,734839,...) ENGINE = InnoDB) */

_____


You can change the number of years as well as the starting month while running the script. If you want 3 years (365*3) partition starting from Jan 1990, use the following syntax:

sh mydate.sh 1990-01-01 1096



<code>
#!/bin/sh
# change the table name and partition column name below

tblname='date_helper'
colname='to_timestamp'

# if no start date is specified, then set the default date to 1 Jan 2010
startdate=${1:-'2010-01-01'}
# 24 partitions for 2 years viz 2010 and 2011 will be created by default
totaldate=${2:-'730'}
# change the days above from 730 for 2 years to 365 for 1 year
# run the script and save the output to a file > torun.sql
# open the file torun.sql and remove the last comma , before executing the query
# mysql test < torun.sql
# CREATE TABLE employees (id INT NOT NULL, store_date date)
# sample table

mysql -e"create table if not exists test.date_helper (id int, to_timestamp datetime);"

mysql -e"drop table if exists test.mycalendar;"
mysql -e"create table test.mycalendar (id int not null auto_increment, dateval date, primary key (id));"

echo "ALTER TABLE $tblname PARTITION BY LIST(to_days($colname)) ("

for (( i = 0 ; i < $totaldate ; i++ ))
do
mysql -e"insert into test.mycalendar (dateval) select '$startdate' + interval $i day;"
done

mysql -Bse"select concat(' PARTITION ', concat(monthname(dateval), extract(year from dateval)), ' VALUES IN ( ') as '', group_concat(concat('to_days(', '\'',dateval,'\')') order by dateval) as '', '), ' as '' from test.mycalendar group by extract(year_month from dateval);" |  sed '$s/,//31'

echo ');'

exit


# use the following syntax to use
# sh /root/calendar.sh '2002-01-01'

## Use the output to create monthly partitions with date 
CREATE TABLE employees (
    id INT NOT NULL,
    store_date date
)
PARTITION BY LIST(to_days(store_date)) (

PARTITION Jan02 VALUES IN (
to_days('2002-01-01'),to_days('2002-01-02'),...
),
PARTITION Feb02 VALUES IN (
to_days('2002-02-01'),to_days('2002-02-02'),...
)
);

# monthly partitions less than 40 years are recommended, in other words not more than 480 partitions 
</code>                
  • shell_script
  • forge
  • oksoft
  • MySQL
                    // To make it work with strings long than 128 characters, change its input and return declarations accordingly.

<code>
DROP FUNCTION IF EXISTS proper;
SET GLOBAL  log_bin_trust_function_creators=TRUE;
DELIMITER |
CREATE FUNCTION proper( str VARCHAR(128) )
RETURNS VARCHAR(128)
BEGIN
  DECLARE c CHAR(1);
  DECLARE s VARCHAR(128);
  DECLARE i INT DEFAULT 1;
  DECLARE bool INT DEFAULT 1;
  DECLARE punct CHAR(17) DEFAULT ' ()[]{},.-_!@;:?/';
  SET s = LCASE( str );
  WHILE i < LENGTH( str ) DO 
    BEGIN
      SET c = SUBSTRING( s, i, 1 );
      IF LOCATE( c, punct ) > 0 THEN
        SET bool = 1;
      ELSEIF bool=1 THEN 
        BEGIN
          IF c >= 'a' AND c <= 'z' THEN 
            BEGIN
              SET s = CONCAT(LEFT(s,i-1),UCASE(c),SUBSTRING(s,i+1));
              SET bool = 0;
            END;
          ELSEIF c >= '0' AND c <= '9' THEN
            SET bool = 0;
          END IF;
        END;
      END IF;
      SET i = i+1;
    END;
  END WHILE;
  RETURN s;
END;
|
DELIMITER ; 
</code>                
  • oksoft
  • MySQL
  • shell_script
  • forge
                    // If you have 2 servers with identical database structure, and some of the tables have different engine type, then create a federated table to connect to the original server and compare the engines type with the current table's engine.  (useful while comparing master - slave tables)

<code>
CREATE TABLE test.`TABLES2` (
`TABLE_CATALOG` varchar(512) default NULL,
`TABLE_SCHEMA` varchar(64) NOT NULL default '',
`TABLE_NAME` varchar(64) NOT NULL default '',
`TABLE_TYPE` varchar(64) NOT NULL default '',
`ENGINE` varchar(64) default NULL,
`VERSION` bigint(21) default NULL,
`ROW_FORMAT` varchar(10) default NULL,
`TABLE_ROWS` bigint(21) default NULL,
`AVG_ROW_LENGTH` bigint(21) default NULL,
`DATA_LENGTH` bigint(21) default NULL,
`MAX_DATA_LENGTH` bigint(21) default NULL,
`INDEX_LENGTH` bigint(21) default NULL,
`DATA_FREE` bigint(21) default NULL,
`AUTO_INCREMENT` bigint(21) default NULL,
`CREATE_TIME` datetime default NULL,
`UPDATE_TIME` datetime default NULL,
`CHECK_TIME` datetime default NULL,
`TABLE_COLLATION` varchar(64) default NULL,
`CHECKSUM` bigint(21) default NULL,
`CREATE_OPTIONS` varchar(255) default NULL,
`TABLE_COMMENT` varchar(80) NOT NULL default ''
)
ENGINE=FEDERATED DEFAULT CHARSET=latin1
CONNECTION='mysql://[email protected]/information_schema/TABLES';

SELECT b.TABLE_SCHEMA as remote_database, b.TABLE_NAME as remote_tableName, b.ENGINE as remote_engine, a.ENGINE AS local_engine 
FROM test.TABLES2 AS a INNER JOIN information_schema.TABLES as b 
ON a.TABLE_SCHEMA = b.TABLE_SCHEMA AND a.TABLE_NAME = b.TABLE_NAME AND a.ENGINE != b.ENGINE;

</code>                
  • shell_script
  • forge
  • oksoft
  • MySQL
                    // A cron to send extract of slow query log of 3 different servers by mail every day. Change the email address. It is assumed that the keys are saved to login to different servers.


<code>
35 23 * * * (ssh 192.29.0.214 mysqldumpslow /var/log/mysql/mysql-slow.log | head -200; echo "#########################"; echo "Slow query log from 121"; echo "#########################"; ssh 192.29.0.121 mysqldumpslow /var/log/mysql/mysql-slow.log | head -200; echo "#########################";  echo "Slow query log from 213"; echo "#########################"; ssh 192.29.0.213 mysqldumpslow /var/log/mysql/mysql-slow.log | head -200 ) | mailx -s "My City slow query log from 214, 121 and 213" [email protected] > /root/shantanu/dumpslowsuccess.txt 2> /root/shantanu/dumpslowerror.txt    
</code>