Showing posts with label Mysql. Show all posts
Showing posts with label Mysql. Show all posts

Friday, July 30, 2010

Auto update Database from one server to another or developement database to live database

The below shell script will take the database backup and uploaded to the svn server. Call this script through cron job so that it will auto execute and send the dbbackup to the svn repo where ever you want. From svn you should auto deploy code to the sever, so run the cron tab in the target server and execute a script which empty the current database and update with this new one. Mostly usefull in while working with drupal, In drupal many things are stored in database instead of files, so that while you developing application, database also updated daily for each module addtion and upgradation etc., So developement database and live database are varies frequently. You can update the files easily using svn but can't update db because we don't know the every change in db while working. In this situation use the below shell script it will update the live database with your development database.

#!/bin/bash
#
# Configuration
#

# Database connection information
dbname="db_name"
dbhost="localhost" # leave as is unless have specific reason to change
dbuser="db_user"
dbpw="db_pass"

# Dump associated information
dump_directory="/path/to/sql/directory" # path to dump dir NO FILE NAME, note end slash
dump_name="dumpname.sql"
logfile=$dump_directory"dumpandcommitt.txt" # name of log file to use

#
# dump db and log on screen and in log file
#
cd $dump_directory
mysqldump --user=$dbuser --password=$dbpw --add-drop-table $dbname > $dump_name
echo " Dumped drupal database, using user:$dbuser; database:$dbname host:$dbhost"
echo " Dumped drupal database, using user:$dbuser; database:$dbname host:$dbhost" >> $logfile

#
# commit the newly dumped db - note you'll need to svn add to repository first before this will work
#
svn commit -m "auto committed db"
echo " Committed new db"
echo " Committed new db" >> $logfile

endtime=`date`
echo "Backup completed $endtime" >> $logfile

Save the above script as db_import_upload.sh
In terminal call as
$ ./db_import_upload.sh

Change mysql table storage engine

Using sql query:
ALTER TABLE products ENGINE = innodb

Using phpmyadmin (GUI) select the table and then do as below images



Thursday, July 8, 2010

CHAR Vs VARCHAR In Mysql

CHAR datatype used when you know the exact length of the value, ex: US Zipcodes (CHAR(7)), Mobile phone numbers (10 numbers only CHAR(10)) etc., And its length should be 0 to 255

VARCHAR datatype used in variable length inputs. Ex; User_firstname (VARCHAR(20)), street_address(VARCHAR(100)) etc.,
Its length should be 0 to 255 before Mysql 5.0.3 version, After 5.3.0 and later versions it should be 0 to 65,535.

See the example below:

Value CHAR(4) Storage Required VARCHAR(4) Storage Required
'' ' ' 4 bytes '' 1 byte
'ab' 'ab ' 4 bytes 'ab' 3 bytes
'abcd' 'abcd' 4 bytes 'abcd' 5 bytes
'abcdefgh' 'abcd' 4 bytes 'abcd' 5 bytes

Monday, July 5, 2010

Backup database using php code

Hello Frineds,
Below code would take entire database backup and store it in the current folder. You can run this script automatically using crop job, so that you would have your database backup for every day or every week as you wish.

//backup_tables('localhost','root','rot','database_name','table_name'); //To backup one specific table
backup_tables('localhost','root','rot','database_name'); // To backup entire database
/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{

$link = mysql_connect($host,$user,$pass);
mysql_select_db($name,$link);

//get all of the tables
if($tables == '*')
{
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}

//cycle through
foreach($tables as $table)
{
$result = mysql_query('SELECT * FROM '.$table);
$num_fields = mysql_num_fields($result);

$return.= 'DROP TABLE '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$return.= "\n\n".$row2[1].";\n\n";

for ($i = 0; $i < $num_fields; $i++)
{
while($row = mysql_fetch_row($result))
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = ereg_replace("\n","\\n",$row[$j]);
if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
if ($j<($num_fields-1)) { $return.= ','; }
}
$return.= ");\n";
}
}
$return.="\n\n\n";
}

//save file
$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
?>

Tuesday, May 4, 2010

Get results by taking user defined starting id

Below query fetched the results as firt row with id 36
SELECT * from users where uid=36 union SELECT * from users where uid!=36

Thursday, April 29, 2010

MYD files in mysql/data/database folder are not shown in database

Hi,
When you copy the database from c:/appserv/mysql/data/ folder instead export from phpmyadmin, and paste the copied database in some other system in c:/appserv/mysql/data/ folder, some times it might not work properly, it creates the database in the phpmyamdin but tables are not shown in that db. Solution for this problem is make sure the folder in c:/appserv/mysql/data/ is writeble and executable, Provide full permissions to this folder to the user who uses the phpmyadmin.

Tuesday, February 2, 2010

Joins in mysql

There are different joins available in mysql to retrieve results from multiple tables.
Join, left join, right join, inner join, outer join

Here i explained each one by taking two tables as an example.

mysql>Products Table;
+----+--------------+--------------+
| id | product_name | manufacturer |
+----+--------------+--------------+
| 1 | Shoes | Company1 |
| 2 | Laptop | Company2 |
| 3 | Monitor | Company3 |
| 4 | DVD | Company4 |
+----+--------------+--------------+
4 rows in set (0.00 sec)

Table buyers:
mysql> SELECT * FROM buyers;
+----+------+------------+----------+
| id | pid | buyer_name | quantity |
+----+------+------------+----------+
| 1 | 1 | Steve | 2 |
| 2 | 2 | John | 1 |
| 3 | 3 | Larry | 1 |
| 4 | 3 | Michael | 5 |
| 5 | NULL | Steven | NULL |
+----+------+------------+----------+
5 rows in set (0.00 sec)

Normal Join

mysql> SELECT buyers.buyer_name, buyers.quantity, products.product_name FROM buyer
s join products on buyers.pid=products.id;
(OR)
mysql> SELECT buyers.buyer_name, buyers.quantity, products.product_name FROM buyer
s,products WHERE buyers.pid=products.id;

+------------+----------+--------------+
| buyer_name | quantity | product_name |
+------------+----------+--------------+
| Steve | 2 | Shoes |
| John | 1 | Laptop |
| Larry | 1 | Monitor |
| Michael | 5 | Monitor |
+------------+----------+--------------+
4 rows in set (0.00 sec)

The above query displays results only with matching pids in both tables.



Left Join

mysql> SELECT buyer_name, quantity, product_name FROM buyers LEFT JOIN products ON
buyers.pid=products.id;
+------------+----------+--------------+
| buyer_name | quantity | product_name |
+------------+----------+--------------+
| Steve | 2 | Shoes |
| John | 1 | Laptop |
| Larry | 1 | Monitor |
| Michael | 5 | Monitor |
| Steven | NULL | NULL |
+------------+----------+--------------+
5 rows in set (0.00 sec)

Explaination:
Mysql starts with the left table (buyers) as main source then For each row from the table buyers mysql scans the table products with pid (i.e id of the product in products table) and returns the product name. Then the product name is joined with the matching row to the table buyers. For unmatched rows it returns null.

The above query is same as below (except with null values)

mysql> SELECT buyers.buyer_name, buyers.quantity, products.product_name FROM buyer
s,products WHERE buyers.pid=products.id;
+------------+----------+--------------+
| buyer_name | quantity | product_name |
+------------+----------+--------------+
| Steve | 2 | Shoes |
| John | 1 | Laptop |
| Larry | 1 | Monitor |
| Michael | 5 | Monitor |
+------------+----------+--------------+
4 rows in set (0.00 sec)

The above query displays results for only matching pids in both tables.

Right Join

mysql> SELECT buyer_name, quantity, product_name FROM buyers RIGHT JOIN products ON
buyers.pid=products.id;
+------------+----------+--------------+
| buyer_name | quantity | product_name |
+------------+----------+--------------+
| Steve | 2 | Shoes |
| John | 1 | Laptop |
| Larry | 1 | Monitor |
| Michael | 5 | Monitor |
| NULL | NULL | DVD |
+------------+----------+--------------+
5 rows in set (0.00 sec)

Explaination:
Mysql starts with the Right table (products) as main source then For each row from the table products mysql scans the table buyers with id (i.e pid of the buyers table) and returns the product name. Then the product name is joined with the matching row to the table products. For unmatched rows it returns null. From my example above it returns NULL for DVD because no one bought DVD.

Inner join is same as join.

The word OUTER may be added after the word LEFT or RIGHT in the left/right joins - it's provided for ODBC compatibility and doesn't add an extra capabilities.

Sql Difference between where clause and Having clause

Hi, below are differences between where clause and having clause in mysql select statements.

1. Having clause is usually used with Group By clause although it can be used without it too.
2. 'Having' is just an additional filter to 'Where' clause.
3. 'Where' clause applies to the individual rows whereas 'Having' clause is used to test some condition on the group(usually aggregate methods) rather than on individual rows.
4. WHERE clause is used to impose condition on SELECT statement as well as single row function and is used before GROUP BY clause where as HAVING clause is used to impose condition on GROUP Function and is used after GROUP BY clause in the query. For example queries look at http://www.allinterview.com/showanswers/6252.html