« Newer Snippets
Older Snippets »
27 total  XML / RSS feed 

Upload Image To Database

// Code To Upload an image to a database and then update its contents.

# Create an ew classified and attach an image with it.
def create
  image_types = ["image/jpeg", "image/pjpeg", "image/gif","image/png", "image/x-png"]
  @categories = Category.find(:all)
  @classified = Classified.new(params[:classified])
  @classified.user = session[:user]
  unless params[:classified][:picture].blank?
    if (image_types.include?params[:classified][:picture].content_type.chomp)
      @classified.picture = params[:classified][:picture].read
    else
      @classified.errors.add(:picture,  "Photo doesn't seem to be JPG, GIF, or PNG. please ensure it is a valid image file.")
      render :action => 'new'
      return
    end
  end

  if @classified.save
    redirect_to :action => 'list'
  else 
    render :action => 'new'
  end
end


# Update Method So user can change the image associated with their classified
def update
  image_types = ["image/jpeg", "image/pjpeg", "image/gif", "image/png", "image/x-png"]
  @classified = Classified.find(params[:id])
  @categories = Category.find(:all)
  
  if @classified.update_attributes(params[:classified])
    unless params[:classified][:picture].blank?
      if (image_types.include?params[:classified][:picture].content_type.chomp)
        @classified.picture = params[:classified][:picture].read
      else
        @classified.errors.add(:picture, " doesn't seem to be JPG, GIF, or PNG. please ensure it is a valid image file.")
        render :action => 'edit'
        return
      end
    end
    
    flash[:notice] = 'Classified was successfully updated.'
    redirect_to :action => 'show', :id => @classified
  else
    render :action => 'edit'
  end
end

Return the MySQL-formatted date for 60 days from today (PHP)

// Get the date in MySQL date format for 60 days from today

$new_expiration_date = date('Y-m-d',mktime(0,0,0,date('m'),date('d')+60,date('Y')));

Backup a single MySQL table

// Use this to take a single table backup, with elements in double quotes delimited with a comma:

while ($row = mysql_fetch_array($query,MYSQL_NUM)) $output .= "\"" . implode("\",\"",str_replace("\r\n"," ",$row)) . "\"\r\n"; echo $output; // or write $output to a file

How to load a sql dump into a new database

// description of your code here

open up iterm

change to the directory with the sql dump you want to load

/usr/local/mysql/bin/mysql --user=root -p

create database mydatabasename default character set utf8;

use mydatabasename;

source mydatabasedump.sql;

show tables;

Converting mysql db to unicode

mysqldump --user=username --password=password --default-character-set=latin1 --skip-set-charset dbname > dump.sql
chgrep latin1 utf8 dump.sql (OR) sed -r 's/latin1/utf8/g' dump.sql > dump_utf.sql
mysql --user=username --password=password --execute="DROP DATABASE dbname; CREATE DATABASE dbname CHARACTER SET utf8 COLLATE utf8_general_ci;"
mysql --user=username --password=password --default-character-set=utf8 dbname < dump.sql

Reset mysql password to old style

SET PASSWORD FOR user@localhost = OLD_PASSWORD('password');

Backup from textdrive to strongspace

#!/bin/sh
# backup script for textdrive to strongspace based on these articles:
# http://help.textdrive.com/index.php?pg=kb.page&id=113
# http://forum.textdrive.com/viewtopic.php?id=10126

# change this!
USER=txd_username
HOME=/users/home/$USER
USER_SS=strongspace_username
PWD_MYSQL=somepassword # chmod 700 this file

# Backup database 
# copy this line for more databases or 
# use --all-databases if you are the main user
# Don't forget to change the database name
/usr/local/bin/mysqldump --opt --skip-add-locks --user=$USER --password=$PWD_MYSQL database1 | gzip > $HOME/backups/database1_`date "+%Y-%m-%d"`.gz
/usr/local/bin/mysqldump --opt --skip-add-locks --user=$USER --password=$PWD_MYSQL database2 | gzip > $HOME/backups/database2_`date "+%Y-%m-%d"`.gz

# Backup subversion (Only works with FSFS)
cd $HOME
tar -z -c -f $HOME/backups/svn_`date "+%Y-%m-%d"`.tar.gz svn

# Add custom dirs here, if you need it, just like the svn example above
# I just keep everything I need in subversion

# Delete old backups
cd $HOME/backups/
/usr/bin/find *.gz -mtime +8 -delete

# Send it to strongspace
/usr/local/bin/rsync -azq --delete -e "ssh -i $HOME/.ssh/ss" $HOME/backups/*.gz $USER_SS@$USER_SS.strongspace.com:/home/$USER_SS/txd-backup/

Daily MySQL backups on Textdrive, rotated weekly

This cron job will create a compressed backup of all the mysql databases under your account. The backup will be stored as "\daily-backup\Mon.gz" - and so forth, one for each day of the week. In this way you will have rotating backups going back seven days.

First, create the "daily-backup" folder under your home directory.

Go into the System - Cron Jobs section in webmin and paste this in as a new cron job (all one line)

/usr/local/bin/mysqldump --skip-opt -uUSERNAME -pPASSWORD --quote-names --complete-insert --extended-insert --quick --compact --lock-tables=false --skip-add-locks --all-databases | gzip > /home/USERNAME/daily-backup/sql-alldb-`date "+%a"`.gz 


Make sure to replace the USERNAME and PASSWORD with your own info.

You can set it up to run on any kind of daily schedule; I have it set to run daily at an early-morning time that I picked randomly.

Small and simple MySQL (and PHP) Connection

<?php
$conn = mysql_connect("DBHOST", "DBUSERNAME", "DBPASSWORD");
mysql_select_db("DBTABLE", $conn) or die(mysql_error());
?>


This is probably the most basic way of connecting to your MySQL database. :)

Back up MySQL databases

Dump all MySQL databases to a location of your choice. I run this as a backup_script from rsnapshot.

This requires the following .my.cnf in the home directory of the user the script runs as (root, when being run from rsnapshot). As it contains an important password, permissions on this file should be 600 (-rw-------).
[client]
user     = root
password = YOUR_MYSQL_ROOT_PASSWORD


#!/bin/bash -e
###########################################################
# Back up MySQL databases
###########################################################

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
PATH="$PATH:/usr/local/mysql/bin"

# My config
#BACKUP_DIR="."

BACKUP_DIR=""

# Do not backup these databases
IGNORE="test"

# Get list of all databases
DB_LIST=`mysql -Bse 'show databases'`

for db in $DB_LIST; do

        # set skip variable
        skip=0

        if [ "$IGNORE" != "" ]; then
                for i in $IGNORE; do
                        [ "$db" == "$i" ] && skip=1 || :
                done
        fi

        if [ "$skip" == "0" ]; then
                mysqldump $db | gzip -9 > $BACKUP_DIR/$db.sql.gz
        fi

done

exit 0



Site map, based on sections (e.g. weblogs) and categories

This will generate a site map using nested lists and h3 & h4 tags. Fairly rough, but serviceable.

{exp:query sql="SELECT blog_name, blog_title, blog_description FROM exp_weblogs"}
<h3><a href="{path={blog_name}}" title="{blog_description}">{blog_title}a></h3>
{exp:weblog:category_archive weblog="{blog_name} "style="nested" orderby="title"}
 {categories}<h4 id="{category_id}"><a href="{path={blog_name}/articles}" title="{category_description}">{category_name}a></h4>{/categories}
 {entry_titles}/detail}">{title}{/entry_titles}
{/exp:weblog:category_archive}
"separator">
{/exp:query}

Convert table character set to UTF8

From http://dev.mysql.com/doc/refman/5.0/en/charset-column.html
----
To change the character set (and collation) for all columns in an existing table, use...
ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name [COLLATE collation_name];
----

ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

How to configure MySQL for UTF8 when running MovableType as FastCGI


Use the modified dispatcher.

#!/usr/bin/perl -w

use strict;
use MT::Bootstrap;
use CGI::Fast;

# preload app packages
use MT::App::CMS;
use MT::App::Comments;
use MT::App::Trackback;
use MT::App::Search;
## uncomment if necessary, but this adds a lot of
## overhead since it loads up LibXML.
##use MT::AtomServer;


my $handlers = {
    'mt.fcgi' => { class => 'MT::App::CMS', name => 'AdminScript' },
    'mt-comments.fcgi' => { class => 'MT::App::Comments', name => 'CommentScript' },
    'mt-tb.fcgi' => { class => 'MT::App::Trackback', name => 'TrackbackScript' },
    'mt-search.fcgi' => { class => 'MT::App::Search', name => 'SearchScript' },
## See note above about this...
##    'mt-atom.fcgi' => { class => 'MT::AtomServer', name => 'AtomScript' },
};

eval {
    while (my $q = new CGI::Fast) {
        my $cgi = $q->script_name;
        $cgi =~ s!.*/!!;
        my $pkg = $handlers->{$cgi}{class};
        die "Invalid handler for $cgi" unless $pkg;
        my $app = $pkg->new(CGIObject => $q) or die $pkg->errstr;
        local $SIG{__WARN__} = sub { $app->trace($_[0]) };
        $app->init_request(CGIObject => $q) unless $app->{init_request};
        fixup_script_names($app);
        
        # do a little nasty over-the-back jump and setup MySQL on every connection        
        my $driver = MT::Object->driver;
        my $dbh = $driver->{dbh};
              my $names_cmd = $dbh->prepare("SET NAMES UTF8");
        $names_cmd->execute();
    
        $app->run;
        my $mode = $app->mode || '';
        if ("$pkg->$mode" eq 'MT::App::CMS->plugin_control') {
            exit; # allows server to recycle after changing plugin switches
        }
    }
};
if ($@) {
    print "Content-Type: text/htmlnn";
    print "Got an error: $@";
}

sub fixup_script_names {
    my ($app) = @_;
    $app->config($handlers->{$_}{name}, $_) foreach keys %$handlers;
}

Search & Replace

update tablename set field = replace(field,'search_for_this','replace_with_this');

Workaround for 'consider upgrading MySQL client' errors

SET PASSWORD FOR 'some_user'@'some_host' = OLD_PASSWORD('mypass');

CRON and MySQL database backup, gzipped

/usr/local/bin/mysqldump --default-character-set=utf8 --user=username --password=password --quote-names --complete-insert --extended-insert --quick --compact --lock-tables=false --skip-add-locks --all-databases | gzip > /home/path/backup/`date "+%Y.%m.%d"`.gz

Make a backup of all tables startin with...

This will backup all tables starting with "prefix_" to a gzipped file backup.sql.gz.

echo "SHOW TABLES" | mysql -uUSERNAME -pPASSWORD -D DBNAME | grep ^prefix_ | xargs mysqldump -uUSERNAME -pPASSWORD DBNAME | gzip -c > backup.sql.gz


You have to replace USERNAME, PASSWORD and DBNAME twice.

Note: On textdrive you want to add --skip-opt to mysqldump, otherwise the command will abort with an error because privs for lockings tables are missing (for me at least).

To check which tables were backed up, you can use:
zcat test.sql.gz | grep CREATE


Read http://dev.mysql.com/doc/mysql/en/mysqldump.html to find out which other options to add to mysqldump

How To Fix MySQL Error 28

MySQL: 1030: got error 28 from server handler

cd /tmp
df -i /tmp
df -h /tmp


Delete anything that�s not supposed to be there.
Stop all databases:

/etc/rc.d/init.d/chkservd stop
/etc/rc.d/init.d/mysql stop


Then fix tables:

cd /var/lib/mysql


Check each letter for errors:

myisamchk -cs a*/*.MYI


Repair where necessary:

myisamchk -r a*/*.MYI
myisamchk -r b*/*.MYI
myisamchk -r c*/*.MYI
myisamchk -r d*/*.MYI
myisamchk -r e*/*.MYI
myisamchk -r f*/*.MYI
myisamchk -r g*/*.MYI
myisamchk -r h*/*.MYI
myisamchk -r i*/*.MYI
myisamchk -r j*/*.MYI
myisamchk -r k*/*.MYI
myisamchk -r l*/*.MYI
myisamchk -r m*/*.MYI
myisamchk -r n*/*.MYI
myisamchk -r o*/*.MYI
myisamchk -r p*/*.MYI
myisamchk -r q*/*.MYI
myisamchk -r r*/*.MYI
myisamchk -r s*/*.MYI
myisamchk -r t*/*.MYI
myisamchk -r u*/*.MYI
myisamchk -r v*/*.MYI
myisamchk -r w*/*.MYI
myisamchk -r x*/*.MYI
myisamchk -r y*/*.MYI
myisamchk -r z*/*.MYI


Turn everything back on:

/etc/rc.d/init.d/chkservd start
/etc/rc.d/init.d/mysql start

Show fields from a Mysql table

SHOW FIELDS FROM `$bd_tabla`

Show tables from a MySQL database

SHOW [FULL|OPEN] TABLES [FROM db_name] [LIKE 'pattern']
« Newer Snippets
Older Snippets »
27 total  XML / RSS feed