Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-10 of 96 total  RSS 

Copy MySQL table

CREATE TABLE table_destination SELECT * FROM table_source ;


CREATE TABLE table_destination LIKE table_source ;
INSERT INTO table_destination SELECT * FROM table_source ;


Source: Asselin Benoit Developpement ( MySQL, SQL )

PHP Dynamic Checkbox Table Creator (data retrieved from MySQL DB)

Hi All.
This is a function for Dynamically Create a Checbox Table retrieving information for from a MySQL Database.
As it is quite commented, it's also good for learning how this things work :)
Hope you find it useful.
Feedback is welcome.
Cheers
Dan

function dynamic_checkbox_table ($sql_str, $col_label, $col_name, $val_checked="S", $cant_cols_tbl=3){
/*
	by Daniel Neumann
	this script creates dynamically permite a table containing checkboxes 
	getting the data for the checkboxes from a MySQL DB
	$sql_str, SQL select string to retrieve data from DB (see example in last comment line)
	$col_label, DB column that has values for the checkbox label 
	$col_name, DB column that has values for the checkbox name
	$val_checked="S", value when checked (value="" attribute) it uses the same value for all of them. If you whish to use a dynamic value from a DB, you should comment the line (it´s explained next to the code in the middle of the function) and de-comment the other line (check the code,. you'll understand what I mean). Also, you should use this parameter to specify the column name for the values
	$cant_cols_tbl=3, quantity of columns for the table, it defaults to 3
	usage example: dynamic_checkbox_table("SELECT * FROM keywords", "Keyword", "ID_Keywrd");
*/
	
	//connect DB and run query
	$db="MyDB";
	$db_user="MyUser";
	$pass="MyPass";
	$host="localhost";
	@mysql_connect($host,$db_user,$pass);
	@mysql_select_db($db) or die ("cannot connect to DB");
	$q_resultado = mysql_query($sql_str);
	mysql_close();
	if (mysql_num_rows($q_resultado)==0) exit("no rows returned");
	
	$next_row = mysql_fetch_array($q_resultado); //fetch first row
	
	$output = "<table  border=\"1\">\n"; //open table tag
	do {
		$output .= "<tr>\n"; //open row tag
		for ($i=1 ; $i <= $cant_cols_tbl ; $i++ ){ //loops as many times as $cant_cols_tbl
			$row=$next_row; //assign $row, next row will be checking next one, that avoids starting a new row when it's gonna be empty
			$output .= "<td>"; //open TD tag
			$output .= (!$row) ? "" : '<input type="checkbox" name="'.$row[$col_name].'" value="'.$val_checked.'" />'.$row[$col_label]; //create checkbox and data from $row (**** you should comment this line if you whish to use dynamic $val_checked****)
//			echo (!$row) ? "" : '<input type="checkbox" name="'.$row[$col_name].'" value="'.$row[$val_checked].'" />'.$row[$col_label]; //create checkbox and data from $row (**** you should de-comment this line if you whish to use dynamic $val_checked****)
			$next_row = mysql_fetch_array($q_resultado); //retrieve next row
			$output .= "</td>\n"; //close TD
		} //close for loop
		$output .= "</tr>\n"; //close row
	} while ($next_row); //close do-while (and checks if there's another row)
	$output .= "</table>\n"; //close table
	return $output; 
}

Transfer Wordpress MySQL database to new webhost

// Transfer Wordpress MySQL database to new webhost in 3 steps (assumes: A. files have already been copied over, B. database created on new server, C. database user created on new server, D. wp-config.php updated on new server)
// 1. login to old host via ssh, run this command:
mysqldump -h DB_HOST -u DB_USER -p DB_NAME > dump.sql

// replace DB_HOST, DB_USER, & DB_NAME with info from the local wp-config.php file
// when asked for password, enter DB_PASSWORD from the local wp-config.php file

// 2. copy dump.sql to your new host using sftp

// 3. login go new host via ssh, run this command:
mysql -h DB_HOST -u DB_USER -p DB_NAME < dump.sql

// replace DB_HOST, DB_USER, & DB_NAME with info from the local wp-config.php file
// when asked for password, enter DB_PASSWORD from the local wp-config.php file

// adopted from this page: http://technosailor.com/2007/04/06/wordpress-faq-how-do-i-move-my-blog-to-a-new-host/

how to create a new user in MySQL

// first, mysql -uroot mysql
// then:


  mysql% GRANT ALL PRIVILEGES ON *.* TO 'jm3_spoon'@'localhost' IDENTIFIED BY 'stirthatshit' WITH GRANT OPTION;
  mysql% create database jm3_agitator;

Rails MySQL/SQLite convenience methods

Usage:

  Person.find :all, :conditions => ["#{sql_year 'birthday'} >= ?", year]


SQLITE = true # or false

def sql_concat(*args)
  SQLITE ? args.join(' || ') : "CONCAT(#{args.join(', ')})"
end

def sql_lcase(expr)
  SQLITE ? "LOWER(#{expr})" : "LCASE(#{expr})"
end

def sql_year(expr)
  SQLITE ? "CAST(STRFTIME('%y', #{expr}) as 'INTEGER')" : "YEAR(#{expr})"
end

def sql_month(expr)
  SQLITE ? "CAST(STRFTIME('%m', #{expr}) as 'INTEGER')" : "MONTH(#{expr})"
end

def sql_day(expr)
  SQLITE ? "CAST(STRFTIME('%d', #{expr}) as 'INTEGER')" : "DAY(#{expr})"
end

def sql_now
  SQLITE ? "CURRENT_TIMESTAMP" : "NOW()"
end

MySQL Dump entire database

mysqldump -v --quick --single-transaction --all-databases -uroot > file.sql

MySQL select query for grouping rows by frequency

SELECT DISTINCT field_name, COUNT(*) AS num FROM table_name GROUP BY field_name ORDER BY num DESC

Regular Expressions with MySQL

SELECT * FROM texts WHERE content REGEXP '[^a-z]Hello[^a-z]' ;


If you really want to force a REGEXP comparison to be case sensitive, use the BINARY keyword to make one of the strings a binary string.
SELECT * FROM texts WHERE content REGEXP BINARY '[^a-zA-Z]Hello[^a-zA-Z]' ;


Warning: some characters do not work. Example :
SELECT * FROM texts WHERE content REGEXP '[^\w]Hello[^\w]' ;


ab-d.fr source code

GPS distance and initial bearing between points (MySQL)

Assume you have a table of locations with Latitude and Longitude for each one. In my case the table is "station" and the primary key is "LocID".

First we create a view to help with the 3D geometry (6378 = Earth's radius in km):
CREATE VIEW gpsGlb AS
    SELECT 
        LocID
        ,6378 * COS(RADIANS(Latitude)) * COS(RADIANS(Longitude)) AS x
        ,6378 * COS(RADIANS(Latitude)) * SIN(RADIANS(Longitude)) AS y
        ,6378 * SIN(RADIANS(Latitude)) AS z
    FROM station;


Here I query for distances to all my locations that are NOT LocID = 405 (rounded miles in my case):
SELECT 
    LocID
    ,ROUND((2 * 6378 * ASIN(d / 2 / 6378)) * 0.621371192) AS dist_mi
FROM
    (SELECT
        SQRT(dx * dx + dy * dy + dz * dz) AS d
        ,LocID
     FROM
        (SELECT
            p1.x - p2.x AS dx
            ,p1.y - p2.y AS dy
            ,p1.z - p2.z AS dz
            ,p2.LocID
        FROM gpsGlb p1
        JOIN gpsGlb p2 ON (p1.LocID = 405 AND p2.LocID != 405)
       ) t1
    ) t2
ORDER BY dist_mi


Here I get the initial bearing to the locations. The "boxed" calculation will come in handy later.
SELECT
    LocID
    ,(360 + DEGREES(ATAN2(y, x))) % 360 AS initBearing_deg
    ,ROUND(((360 + DEGREES(ATAN2(y, x))) % 360) / 22.5) * 22.5 
     AS initBearingBoxed_deg
FROM
    (SELECT
        SIN(RADIANS(s2.Longitude - s1.Longitude)) * COS(RADIANS(s2.Latitude)) 
        AS y
        ,COS(RADIANS(s1.Latitude)) * SIN(RADIANS(s2.Latitude))
            - SIN(RADIANS(s1.Latitude)) * COS(RADIANS(s2.Latitude))
               * COS(RADIANS(s2.Longitude - s1.Longitude)) 
        AS x
        ,s2.LocID
    FROM station s1
    JOIN station s2 ON (s1.LocID = 405 AND s2.LocID != 405)
    ) q1


Here's the combined query plus boxed degrees converted to 'NNE', etc. I've also added a limit for the distance in the qq1 subquery.
SELECT
    qq2.LocID
    ,dist_mi
    ,CASE initBearingBoxed_deg
        WHEN 22.5 THEN 'NNE'   WHEN 45 THEN 'NE'
        WHEN 67.5 THEN 'ENE'   WHEN 90 THEN 'E'
        WHEN 112.5 THEN 'ESE'  WHEN 135 THEN 'SE'
        WHEN 157.5 THEN 'SSE'  WHEN 180 THEN 'S'
        WHEN 202.5 THEN 'SSW'  WHEN 225 THEN 'SW'
        WHEN 247.5 THEN 'WSW'  WHEN 270 THEN 'W'
        WHEN 292.5 THEN 'WNW'  WHEN 315 THEN 'NW'
        WHEN 337.5 THEN 'NNW'  ELSE 'N'
     END AS bearing
FROM (
    SELECT 
        LocID
        ,ROUND((2 * 6378 * ASIN(d / 2 / 6378)) * 0.621371192) AS dist_mi
    FROM
        (SELECT
            SQRT(dx * dx + dy * dy + dz * dz) AS d
            ,LocID
         FROM
            (SELECT
                p1.x - p2.x AS dx
                ,p1.y - p2.y AS dy
                ,p1.z - p2.z AS dz
                ,p2.LocID
            FROM gpsGlb p1
            JOIN gpsGlb p2 ON (p1.LocID = 405 AND p2.LocID != 405)
           ) t1
        ) t2
    ) qq1
JOIN (
    SELECT
        LocID
        ,(360 + DEGREES(ATAN2(y, x))) % 360 AS initBearing_deg
        ,(360 + ROUND((DEGREES(ATAN2(y, x))) / 22.5) * 22.5) % 360 
         AS initBearingBoxed_deg
    FROM
        (SELECT
            SIN(RADIANS(s2.Longitude - s1.Longitude)) * COS(RADIANS(s2.Latitude)) 
             AS y
            ,COS(RADIANS(s1.Latitude)) * SIN(RADIANS(s2.Latitude))
                - SIN(RADIANS(s1.Latitude)) * COS(RADIANS(s2.Latitude))
                   * COS(RADIANS(s2.Longitude - s1.Longitude)) 
             AS x
            ,s2.LocID
        FROM station s1
        JOIN station s2 ON (s1.LocID = 405 AND s2.LocID != 405)
        ) q1
    ) qq2 ON (qq1.LocID = qq2.LocID
              AND qq1.dist_mi <= 60)
ORDER BY dist_mi

Detect Daylight Saving Time on a MySQL server in the America/New_York timezone.

SELECT -5 - CAST(REPLACE(TIMEDIFF(NOW(), UTC_TIMESTAMP()), ':00:00', '') AS SIGNED) AS isDst

To test in other timezones, replace -5 with your local standard time GMT offset.
« Newer Snippets
Older Snippets »
Showing 1-10 of 96 total  RSS