Wednesday, 4 July 2018

Upload Image to MySQL using PHP

Upload Image to MySQL using PHP
As a new-bie to php/mysql, I tried different stuffs. So here I’m with my php code for Image Upload to MySQL. Its a quite simple code with two php files one to display and one to upload.
For Image Upload code, I’ve added code download link upload-image-mysql-demo.zip at the end of the page.
As a new-bie to php/mysql, I tried different stuffs. So here I’m with my php code for Image Upload to MySQL. Its a quite simple code with two php files one to display and one to upload.

CREATE TABLE `pix` (
`pic_id` int(11) NOT NULL auto_increment,
`pic_name` varchar(100) NOT NULL,
`pic_data` longblob NOT NULL,
PRIMARY KEY  (`pic_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Get 2 php files:- Image.php, showImage.php.
Set Connection parameters accordingly.
/* Image.php*/
<?php
$con = mysql_connect(“127.0.0.1:3306″,”root”,””);
if (!$con)
{
die(“Could not connect: ” . mysql_error());
}
$DB = mysql_select_db(“test”, $con);
move_uploaded_file($_FILES[“uploadedfile”][“tmp_name”],”latest.img”);
$instr = fopen(“latest.img”,”rb”);
$image = addslashes(fread(fopen(“latest.img”,”r”),filesize(“latest.img”)));
mysql_query (“insert into pix (pic_name, pic_data) values (“myImage”, “‘.$image.'”);”);
?>
<html>
<form enctype=”multipart/form-data” method=”POST”>
<img src=showImage.php?gim=1 width=500 height=150 alt=”hell”>
<br><hr>
<input type=”hidden” name=”MAX_FILE_SIZE” value=”100000″ />
Choose a file to upload(<100 KB): <input name=”uploadedfile” type=”file” /><br/>
<input type=”submit” value=”submit” name=”submit” />
</form>
<html>
/*showImage.php*/
<?php
$con = mysql_connect(“127.0.0.1:3306″,”root”,””);
if (!$con)
{
die(“Could not connect: ” . mysql_error());
}
$DB = mysql_select_db(“test”, $con);
$res = @mysql_query(“select * from pix order by pic_id desc limit 1”);
if ($row = @mysql_fetch_assoc($res))
{
$title = htmlspecialchars($row[pic_name]);
$bytes = $row[pic_data];
}
header(“Content-type: image/jpg”);
print $bytes;
mysql_close();
?>

Using MySQLTuner – MySQL Optimization Tool

Using MySQLTuner – MySQL Optimization Tool
MySQLTuner is a script written in Perl that will assist you with your MySQL configuration and make recommendations for increased performance and stability. Within seconds, it will display statistics about your MySQL installation and the areas where it can be improved.
Downloading MySQLTuner:
wget http://mysqltuner.com/mysqltuner.pl
chmod +x mysqltuner.pl
Using MySQLTuner Script for Lampp systems:
Just replace mysql & mysqladmin commands with respect lampp commands
vi mysqltuner.pl
Press Keys:- <ESC> and <:>
Enter:- 1,$s/\`mysql/\`\/opt\/lampp\/bin\/mysql/g
Running mysqltuner and obtaining the performance analysis:
Shell> ./mysqltuner.pl
Following is the Sample Output from mysqltuner script::
>>  MySQLTuner 1.0.0 – Major Hayden
>>  Bug reports, feature requests, and downloads at http://mysqltuner.com/
>>  Run with ‘–help’ for additional options and output filtering
Please enter your MySQL administrative login: root
Please enter your MySQL administrative password:
——– General Statistics ——————————–
[–] Skipped version check for MySQLTuner script
[OK] Currently running supported MySQL version 5.0.27-log
[!!] Switch to 64-bit OS – MySQL cannot currently use all of your RAM
——– Storage Engine Statistics ————————-
[–] Status: +Archive -BDB -Federated -InnoDB -ISAM -NDBCluster
[–] Data in MyISAM tables: 33G (Tables: 1013)
[–] Data in ARCHIVE tables: 22B (Tables: 1)
[!!] Total fragmented tables: 71
——– Performance Metrics ——————————-
[–] Up for: 22d 7h 48m 16s (2B q [1K qps], 557K conn, TX: 1B, RX: 3B)
[–] Reads / Writes: 15% / 85%
[–] Total buffers: 1.2G global + 12.3M per thread (100 max threads)
[!!] Allocating > 2GB RAM on 32-bit systems can cause system instability
[!!] Maximum possible memory usage: 2.4G (59% of installed RAM)
[OK] Slow queries: 0% (7K/2B)
[OK] Highest usage of available connections: 25% (25/100)
[OK] Key buffer size / total MyISAM indexes: 1.0G/4.6G
[OK] Key buffer hit rate: 99.7% (8B cached / 30M reads)
[OK] Query cache efficiency: 49.2% (1M cached / 2M selects)
[OK] Query cache prunes per day: 0
[OK] Sorts requiring temporary tables: 0% (207 temp sorts / 49M sorts)
[OK] Temporary tables created on disk: 9% (46K on disk / 511K total)
[OK] Thread cache hit rate: 99% (269 created / 557K connections)
[!!] Table cache hit rate: 0% (64 open / 1M opened)
[OK] Open file limit used: 10% (112/1K)
[OK] Table locks acquired immediately: 99% (224M immediate / 224M locks)
——– Recommendations ———————————–
General recommendations:
Run OPTIMIZE TABLE to defragment tables for better performance
Increase table_cache gradually to avoid file descriptor limits
Variables to adjust:
table_cache (> 64)

Perl Script for Analyze – Optimize – Repair Mysql Databases

Perl Script for Analyze – Optimize – Repair Mysql Databases
The perl script is mainly created to avoid manual Mysql Server Maintenance. The script uses Perl module DBI. You need to provide access credentials and database name(optional). Regarding Analyse, Optimize and Repair you may ofcourse refer dev.mysql.com.
OPTIMIZE TABLE should be used if you have deleted a large part of a table or if you have made many changes to a table with variable-length rows (tables that have VARCHAR, VARBINARY, BLOB, or TEXT columns). Deleted rows are maintained in a linked list and subsequent INSERT operations reuse old row positions. You can use OPTIMIZE TABLE to reclaim the unused space and to defragment the data file.
REPAIR TABLE repairs a possibly corrupted table. By default, it has the same effect as myisamchk –recover tbl_name. REPAIR TABLE works for MyISAM and for ARCHIVE tables.
ANALYZE TABLE analyzes and stores the key distribution for a table. During the analysis, the table is locked with a read lock for MyISAM and BDB. For InnoDB the table is locked with a write lock. This statement works with MyISAM, BDB, and InnoDB tables. For MyISAM tables, this statement is equivalent to using myisamchk –analyze.
The perl script is mainly created to avoid manual Mysql Server Maintenance. The script uses Perl module DBI. You need to provide access credentials and database name(optional). Regarding Analyse, Optimize and Repair you may ofcourse refer dev.mysql.com.
OPTIMIZE TABLE should be used if you have deleted a large part of a table or if you have made many changes to a table with variable-length rows (tables that have VARCHAR, VARBINARY, BLOB, or TEXT columns). Deleted rows are maintained in a linked list and subsequent INSERT operations reuse old row positions. You can use OPTIMIZE TABLE to reclaim the unused space and to defragment the data file.
REPAIR TABLE repairs a possibly corrupted table. By default, it has the same effect as myisamchk –recover tbl_name. REPAIR TABLE works for MyISAM and for ARCHIVE tables.
ANALYZE TABLE analyzes and stores the key distribution for a table. During the analysis, the table is locked with a read lock for MyISAM and BDB. For InnoDB the table is locked with a write lock. This statement works with MyISAM, BDB, and InnoDB tables. For MyISAM tables, this statement is equivalent to using myisamchk –analyze.
use DBI;
my $username;
my $password;
my $hostname;
my $dbName;
my $databasez;
my $withRepair = 0; #1=enabled ##Also checks and repairs the table if required.
$username='USERNAME';
$password='PASSWORD';
$hostname='HOSTNAME';
$dbName=''; #(Optional) considers all if left blank
$databasez='';
$dbName ='';
my $port = 3307;
my $dbh;


$dbh = DBI->connect("dbi:mysql:database=$dbName;host=$hostname;$port", trim($username), trim($password)) or die "$DBI::errstr";

if(length(trim($databasez)) == 0)
{
my $db_SQL="SHOW DATABASES;";
$sth=$dbh->prepare($db_SQL);
$sth->execute();

while($databasez = $sth->fetchrow_array())
{
if ((trim($databasez) eq "information_schema") or (trim($databasez) eq "mysql")) {
next;
}
tablesCount($databasez);
}
}
else {
tablesCount($databasez);
}

sub trim($)
{
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}

sub execute($)
{
my $sth_analyze_table = $dbh->prepare(shift);
$sth_analyze_table->execute() or $dbh->errstr;
my $status2 = $sth_analyze_table->fetchrow_array();
printf "%35s %10s %10s\n",$tablez,$status,$status2;
}

sub tablesCount($)
{
my $Line = "-----------------";
printf "\n%20s\n",$Line;
printf "\nDatabase:%35s\n",$databasez;
printf "\n%35s %10s %10s\n","Table Name" ,"Status", "Repair Status";
printf "\n%20s\n",$Line;
my $tables_SQL = "SHOW TABLES FROM $databasez;";
my $sth_table=$dbh->prepare($tables_SQL);
$sth_table->execute();
while($tablez = $sth_table->fetchrow_array())
{
my $analyze_tables_SQL = "ANALYZE TABLE $databasez.$tablez;";
my $optimize_table_SQL = "OPTIMIZE TABLE $databasez.$tablez;";
my $check_tables_SQL = "repair table $databasez.$tablez;";

execute($analyze_tables_SQL);
execute($optimize_table_SQL);

if ($withRepair == 1)
{
my $check_tables_SQL = "check table $databasez.$tablez;";
my $sth_check_table=$dbh->prepare($check_tables_SQL);
$sth_check_table->execute() or $dbh->errstr;
my $status = $sth_check_table->fetchrow_array();

if(trim($status) ne 'OK')
{
print "Attempting Repair: $databasez.$tablez \n";
my $check_tables_SQL = "repair table $databasez.$tablez;";
execute($check_tables_SQL);
my $status2 = $sth_check_table->fetchrow_array();
printf "%35s %10s %10s\n",$tablez,$status,$status2;
}
else
{
printf "%35s %10s %10s\n",$tablez,$status,"NA";
}
}
}
}

MySQL Master Master Replication and auto_increment_increment / auto_increment_offset

MySQL Master Master Replication and auto_increment_increment / auto_increment_offset

In this post we will see importance of replication related variables auto_increment_increment & auto_increment_offset with respect to MySQL Master Master setup.
Consider we’ve already set a master-master replication. Now create following table on Server1:
CREATE TABLE `temp` (
`id` int(10) NOT NULL auto_increment,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=latin1;
The table will will get replicated on Mysql Server2 in the master-master setup.
Now insert value on Mysql Server1 as follows:
mysql>insert into temp values(null);
On Mysql Server2 in replication you will see single row inserted. Now insert one row from Mysql Server2 as follows:
mysql>insert into temp values(null);
You should see an error:
Error ‘Duplicate entry ‘1’ for key ‘PRIMARY” on query…
The obvious problem of maintaining auto increments in sync will persist on both mysql servers as AUTO_INCREMENT’s value.
The solution is to use the variables auto_increment_increment and auto_increment_offset as explained below.
– Stop both master-master replication servers.
– Add variables to my.[ini|cnf] file.
Server1:
auto_increment_increment=2
auto_increment_offset=2
Server2:
auto_increment_increment=2
auto_increment_offset=1
– Restart mysql servers.
– Start slave.
Remember:
– auto_increment_increment controls the interval between successive column values.
– auto_increment_offset determines the starting point for the AUTO_INCREMENT column value.
– It’s advisable to have these configured to avoid any accidental conflicts for all master-master setup.

Search / find through all databases, tables, columns in MySQL

Search / find through all databases, tables, columns in MySQL

What will you do if one day some one ask you to find single string in all databases, all tables and in all columns?
I just read such question and tried to find a “ready made” solution.
Reusability is Key Concept !!
But I ended up finding no “copy-paste” material. Some of the posts like http://vyaskn.tripod.com/search_all_columns_in_all_tables.htm helped me out and supported my thinking of “how to do it” !
Here is how I did it – Search through all databases – tables – columns:
  • Create a table for storing output.
  • Loop through information_schema database’s COLUMNS table to obtain alldatabases, table and column names.
  • Execute a count(*) query on database.table for each column with appropriate search string in where condition.
  • If count(*) > 0, that perticular column has the search term.
  • Insert that triplet (database name, table name, column name) in to a table.
  • Select * from table to view respective database,table and column names having the search term.
## Procedure for search in all fields of all databases
DELIMITER $$
#Script to loop through all tables using Information_Schema
DROP PROCEDURE IF EXISTS get_table $$
CREATE PROCEDURE get_table(in_search varchar(50))
READS SQL DATA
BEGIN
DECLARE trunc_cmd VARCHAR(50);
DECLARE search_string VARCHAR(250);
DECLARE db,tbl,clmn CHAR(50);
DECLARE done INT DEFAULT 0;
DECLARE COUNTER INT;
DECLARE table_cur CURSOR FOR
SELECT concat('SELECT COUNT(*) INTO @CNT_VALUE FROM `',table_schema,'`.`',table_name,'` WHERE `', column_name,'` REGEXP "',in_search,'"') ,table_schema,table_name,column_name FROM information_schema.COLUMNS WHERE TABLE_SCHEMA IN ('network_detail');
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
#Truncating table for refill the data for new search.
PREPARE trunc_cmd FROM "TRUNCATE TABLE temp_details;";
EXECUTE trunc_cmd ;
OPEN table_cur;
table_loop:LOOP
FETCH table_cur INTO search_string,db,tbl,clmn;
#Executing the search
SET @search_string = search_string;
#SELECT search_string;
PREPARE search_string FROM @search_string;
EXECUTE search_string;
SET COUNTER = @CNT_VALUE;
#SELECT COUNTER;
IF COUNTER>0 THEN
# Inserting required results from search to table
INSERT INTO temp_details VALUES(db,tbl,clmn);
END IF;
IF done=1 THEN
LEAVE table_loop;
END IF;
END LOOP;
CLOSE table_cur;
#Finally Show Results
SELECT concat("SELECT * FROM ",t_table, " WHERE ", t_field, " REGEXP '", in_search, "';") FROM temp_details;
END $$
DELIMITER ;
No wonder you will find the variable naming has not been taken care of; but its forgivable!

Download the code here: find in all databases-tables.sql

Well this thing worked for me in 5.0.83-community-nt-log on windows machine. I dropped idea of creating temporary table through procedure to store and display results considering a bug and deciding to adopt the easy way out though its v.old.

MySQL Resources

MySQL Resources

This page includes the important and useful resources links for MySQL Server.
MySQL Downloads and Documentation:
MySQL Community Server (Current Generally Available Release)
http://dev.mysql.com/downloads/mysql/
MySQL Workbench
http://dev.mysql.com/downloads/workbench/
MySQL Product Archives
http://downloads.mysql.com/archives.phpMySQL
MySQL Cluster
http://dev.mysql.com/downloads/cluster/
MySQL Proxy
http://dev.mysql.com/downloads/mysql-proxy/
MySQL Documentation: MySQL Reference Manuals
http://dev.mysql.com/doc/
Sample Databases | Documentation Repositories | Community Contributed Doc
http://dev.mysql.com/doc/index-other.html
Browse MySQL Documentation by Topic
http://dev.mysql.com/doc/index-topic.html
Optimization, Monitoring  & Development Tools for MySQL Server:
Innotop: innotop is a ‘top’ clone for MySQL with more features and flexibility than similar tools.
http://code.google.com/p/innotop/
MaatKit: Maatkit is a well-documented toolkit for users, developers, and administrators of open-source databases.
http://www.maatkit.org/
MySQL Tuner: MySQLTuner is a script written in Perl that will assist you with your MySQL configuration and make recommendations for increased performance and stability.
http://mysqltuner.pl/mysqltuner.pl
https://github.com/rackerhacker/MySQLTuner-perl
MyTOP: mytop is a console-based (non-gui) tool for monitoring the threads and overall performance for MySQL Server.
http://jeremy.zawodny.com/mysql/mytop/
OpenArk-Kit: The openark kit is a set of utilities for MySQL. They solve everyday maintenance tasks, which may be complicated or time consuming to work by hand.
http://code.openark.org/forge/openark-kit
Miscellaneous:
Nagios: Nagios Is The Industry Standard In IT Infrastructure Monitoring.
http://www.nagios.org/
Blogs, Podcasts and readings:
http://planet.mysql.com/
http://dev.mysql.com/librarian/
http://technocation.org/
MySQL Books:
coming soon...