Wednesday, May 18, 2011

PHP - Alternate color divs using variable variables in a loop

If writing repetitive code, it is simple to instead loop thorugh an array, repeating the same code for each value. But to style it in a more interesting way than it all being the same, variable variables can be used to alter the style at each iteration of the loop...


<?php
$array = array("value one", "value two", "value three");
$color1="#e92e27";
$color2="#507FF7";
$color3="#e8e507";

$i="1";

foreach($array as $val)
{
if($i==4){$i="1";}

echo "<div style='width:150px;border:4px ".${color.$i}." solid;background-color:#ffffff;margin:5px;padding:5px;'>";

echo $val;

echo "</div>";
$i++;
}
?>

Any number of colors and any number of values can be added. This is useful if the list of values is long.

The result of the above code would look like this....



value one


value two


value three

Tuesday, May 17, 2011

PHP - Get Current Page URL

Returns variable $url as http://www.site.com/file.htm

//get current url
$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];

Monday, May 16, 2011

php - split mysql results into groups

When displaying a set of mysql results, sometimes it is practical to show them in groups, rather than one long list. This is useful for page design, so you can split results into divs or table cells.

Maybe mysql has a command for that, but so far I can only see that it can be done in php as follows...

(The following php code loops through a mysql result, and every five will be split and displayed into separate inline divs.)

<?php

//get the mysql resource
$result=mysql_query("SELECT column FROM table") or die(mysql_error());

//start $d at 0
$d=0;

//start first div before the loop
echo "<div style='width:150px;border:thin #FF00FF solid;float:left;display:inline;margin:5px;padding:5px;'>";

//loop through results incrementing $d and printing as per if conditions
while ($row = mysql_fetch_array($result))
{
$column=$row['column'];

//the first condition stops zero rows being shown in the first div
if($d== 0){
echo $column."<br />";
$d++;
}

//second condition prints the div code when $d is divisible by 5, so every 5 results
elseif($d % 5 == 0){
echo "</div><div style='width:150px;border:thin #FF00FF solid;float:left;display:inline;margin:5px;padding:5px;'>";
echo $column."<br />";
$d++;
}

//third condition prints results within the divs
elseif($d % 5 != 0){
echo $column."<br />";
$d++;
}
else{}

}//endwhile

//close the last div tag
echo "</div>";
?>


This php code loops through a mysql result, and every five will be split and displayed into separate inline divs.

Friday, May 06, 2011

Kate Middleton Pictures


I took some pictures of Kate Middleton on her wedding day by doing screen shots of the youtube live stream. I think she looks a little like Kate Perry in this one.

I put the rest on hairstylezone.com here ... Kate Middleton Hairstyles

Removing header from mysql output in bash

So I had been using a conditional statement to remove the column name from the output of a mysql query in bash. I found today that the header can be suppressed using --silent and --skip-column-names parameters in the mysql. As shown in mysql command options
##MYSQL QUERY##
variable=$(
mysql -sN -u username --password=password << eof use databasename; SELECT id FROM tablename; eof)


It is possible to alter a variable using parameter substitution as follows :
variable=${variable#id}
variable=${variable#*$'\n'}
variable="${x//$'id\n'}"
The 1st just removes the string "id", the 2nd removes everything up to the first new line and the 3rd removes all instances of the string "id" +newline. As suggested at Linux Questions


When returning the results in a for loop, the -n parameter for echo, removes the new line that is otherwise there.

##for each##
for ARG in $variable
do
echo -n $ARG
done

Saturday, April 30, 2011

PHP To Loop Through Alphabet & Display Categories

The alphabet can be incremented in PHP like numbers can, so incrementing through an alphabetical list is possible.

$capital="A";
$capital++;
echo $capital;
(returns b)

To write all 26 letters of the alphabet
$capital=A;
for ($i=1; $i<=26; $i++)
{
echo $capital;
$capital++;
}
(returns whole alphabet)

I wanted to display categories, in divs, in alphabetical order, querying a database to get categories beginning with each letter, to display in the div corresponding to that letter.

It ends up looking like this...



I set css properties for the divs as follows..
.prop{
height:200px;
float:right;
width:1px;
display:inline;
padding:5px;
margin:5px;
float:left;
width:160px;
border-style:solid;
border-width:2px;
border-color:#2491EE;
}

The php I did as follows...


$capital=A;
for ($i=1; $i<=26; $i++)

{
/*echoes the current letter, images could be used if named A.jpg B.jpg etc*/

echo "<div class=\"prop\"> <strong>".$capital."</strong><br />";

/*The mysql quries a category table returning all categories beginning the current letter*/
$result=mysql_query("SELECT category FROM categories WHERE category REGEXP '^".$capital."' ORDER BY category") or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$cat= $row['category'];

/*the following line echoes the category name and links to a category page, passing the name as a variable*/
echo "<a href='category.htm?category=$cat'>".$cat."</a><br />";
}
echo "</div>";
$capital++;
}

Monday, April 25, 2011

Comparing Dates In Epoch Seconds

I put together this script to check the date in a table, convert it to epoch seconds, and then check todays date minus seven days in epoch seconds, to make it possible to do a comparison (greater than) for the dates. So if a date is within the last week, it is returned.

Not so necessary for just seven dates as they could each be declared individually, but for any greater date range would be useful, as converting to epoch seconds means that the two dates can be compared as to which is greater, with later dates obviously being greater than....



#!/bin/sh

#GET CURRENT DATE IN EPOCH SECONDS#

export todaysdate=`date +%s`

#7DAYS AGO IS -604800 SECONDS#
sevendaysago="$(( $todaysdate - 604800 ))"

#QUERY DATABASE TO GET MERCHANT ID ANF LOOP THROUGH EACH#

merchant=`
mysql -u username --password=password << eof
use databasename;
SELECT merchantid FROM tablename;
eof`


for ARG1 in $merchant
do

#QUERY DATABASE TO GET DATE DATA WAS ALTERED FOR EACH MERCHANT#
date=`
mysql -u username --password=password << eof
use database;
SELECT lastUpdated FROM tablename WHERE merchantid='$ARG1';
eof`

for ARG2 in $date
do

#IGNORE COLUMN NAME IN RETURNED RESULT#
if [ "$ARG2" != "lastUpdated" ]; then
#CONVERT DATE TO EPOCH SECONDS#
export recordeddate=`date -d "$ARG2" +%s`


#COMPARE RECORDED DATE TO DATE SEVEN DAYS AGO#
if [ $recordeddate -gt $sevendaysago ]; then

#DO WHATEVER#
echo $ARG1 data changed in the last seven days on $ARG2

fi
fi
done
done


Linux Questions

Wednesday, April 20, 2011

Shell Script Useful Snippets

Returns todays date mysql style(2011-04-20)

#!/bin/sh

today=`eval date +%Y-%m-%d`
echo $today




Returns yesterdays date mysql style(2011-04-19)

#!/bin/sh

yesterday=`eval date --date=yesterday +%Y-%m-%d`
echo $yesterday



Returns last seven days dates mysql style(2011-04-20) (alternative method for greater number of dates in range http://www.linuxquestions.org/questions/programming-9/bash-script-date-range-876326/)

#!/bin/sh

export yesterday=`date --date="yesterday" +%Y-%m-%d`
export twodaysago=`date --date="2 days ago" +%Y-%m-%d`
export threedaysago=`date --date="3 days ago" +%Y-%m-%d`
export fourdaysago=`date --date="4 days ago" +%Y-%m-%d`
export fivedaysago=`date --date="5 days ago" +%Y-%m-%d`
export sixdaysago=`date --date="6 days ago" +%Y-%m-%d`
export sevendaysago=`date --date="7 days ago" +%Y-%m-%d`

echo yesterday was $yesterday
echo two days ago was $twodaysago
echo three days ago was $threedaysago
echo four days ago was $fourdaysago
echo five days ago was $fivedaysago
echo six days ago was $sixdaysago
echo seven days ago was $sevendaysago



bash script For Each Loop On mysql result -dont know why but the column name is returned in the results loop as the first result, so i put a condition to oly return if it was not the column name, that loops through all the values.

#!/bin/sh

##MYSQL QUERY##
variable=`
mysql -u username --password=password << eof
use databasename;
SELECT somecolumn FROM table WHERE anothercolumn='2011-04-19';
eof`

##for each##

for ARG in $variable
do
if [ "$ARG" != "somecolumn" ]; then
echo $ARG was updated yesterday
fi
done


Tuesday, April 19, 2011

Bash Script - MYSQL query (match files in directory with certain files in db table)

Get all files in a directory, compare it to filenames stored in database, where a condition is met and return only the filenames that match that condition.



#!/bin/bash

##GET & LOOP THROUGH FILES IN DIRECTORY##
cd /path/to/directory/
##FIND ALL TEXT FILES##
FILES=*.txt
for f in $FILES
do

##GET TXT FILENAME##
TXTFNAME="$f"

##ALTER IF NECESSARY##
export TXTFNAME1=`echo $TXTFNAME | sed -e 's/fromthis/tothis/g'`

##MYSQL QUERY##
variable=`
mysql -u username --password=password << eof
use databasename;
SELECT column FROM table WHERE column='keyword';
eof`

##IF FILENAME EQUALS FILENAME IN DB##
if [[ $variable =~ .*$TXTFNAME1.* ]]; then

echo $TXTFNAME1 is a match


fi

#end of loop#
done

Sunday, April 17, 2011

php change date format for inserting into MYSQL

This code is based on http://40shadows.wordpress.com/2008/09/30/change-date-format-in-php/

//input format: d/m/yy or yyyy
$date = '24/12/08';
$dtmp = explode("/",$date);
$dadate = mktime(0,0,0,$dtmp[1],$dtmp[0],$dtmp[2]);
echo date('d-m-Y',$dadate);
//outputs 24-12-2008


//input format: yyyy-m-d
$date2 = '2011-04-25';
$dtmp = explode("-",$date2);
$dadate2 = mktime(0,0,0,$dtmp[1],$dtmp[2],$dtmp[0]);
echo date('d/m/Y',$dadate2);
//outputs 25/04/2011

Full Text Search MySQL

Create a table called extypes, with 3 columns, ID , description and calpermin

CREATE TABLE IF NOT EXISTS `extypes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` text NOT NULL,
`calpermin` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

Insert some values into the table

INSERT INTO `extypes` (`id`, `description`, `calpermin`) VALUES
(1, 'Rowing Machine Moderate', 6),
(2, 'Walking Moderate', 4),
(3, 'Shopping With Trolley', 2),
(4, 'Dancing Moderate', 2),
(5, 'Dancing Vigorous', 4)

Make the description column searchable

ALTER TABLE `extypes` ADD FULLTEXT `search_index` (
`description`)

Search for the keyword "rowing" in the description

SELECT * from extypes WHERE MATCH (description) AGAINST('rowing')

Thursday, April 07, 2011

Mod_Pagespeed Update On Linux With cPanel & WHM

I started using a really good new mod, mod_pagespeed on my server that speeds up web page delivery alot. It can be put in Virtual Hosts for individual websites, or applied to all websites on a server.

If a server has cpanel/whm installed, manually updates are required when a new release comes out, so I wrote a bash script to put in cron.monthly to do this. It is based on the original installation guide at http://i-comers.com/showthread.php?t=1598691

It just checks to see if the file at code.google.com is newer than the file on the server and then goes through the various installation commands, if it is, then restarts httpd. The sed section could be further modified to include any specific config that is in pagespeed.conf, but my config is in virtual hosts so I can just rewrite the paths to the mods and switch it off there and leave the config as is in httpd.conf, virtual hosts. Although it would be worth checking whether any changes have been made in the new version of pagespeed.conf, that I have not written into the code, just an email to tell me if updated, so that can be checked manually against the bak version, because the config file, as far as I know, usually stays the same....

#!/bin/bash

##if date of remote file is newer than date of local file then update mod pagespeed##

if [[ https://dl-ssl.google.com/dl/linux/direct/mod-pagespeed-beta_current_x86_64.rpm -nt /usr/local/src/mod_pagespeed/mod-pagespeed-beta_current_x86_64.rpm ]]; then


echo Mod_Pagespeed Upgrade Required!

##remove previous version##
rm -r /usr/local/src/mod_pagespeed/

cd /usr/local/src
mkdir mod_pagespeed
cd mod_pagespeed
##this is the specific rpm url required for download from google##
wget https://dl-ssl.google.com/dl/linux/direct/mod-pagespeed-beta_current_x86_64.rpm

rpm2cpio mod-pagespeed-beta_current_x86_64.rpm | cpio -idmv
cp /usr/local/src/mod_pagespeed/usr/lib64/httpd/modules/mod_pagespeed.so /usr/local/apache/modules/

##bakup previous pagespeed config##
cp /usr/local/apache/conf/pagespeed.conf /usr/local/apache/conf/pagespeedbak.conf

##the following sed commands rewrite parts of pagespeed.conf as required for different paths to files on cpanel servers. Changes should be made as per each individuals pagespeed.conf requirements.##

sed -i 's/ModPagespeed on/ModPagespeed off/g' /usr/local/src/mod_pagespeed/etc/httpd/conf.d/pagespeed.conf

sed -i 's/LoadModule pagespeed_module \/usr\/lib64\/httpd\/modules\/mod_pagespeed\.so/LoadModule pagespeed_module modules\/mod_pagespeed\.so/g' /usr/local/src/mod_pagespeed/etc/httpd/conf.d/pagespeed.conf

sed -i 's/LoadModule deflate_module \/usr\/lib64\/httpd\/modules\/mod_deflate\.so/LoadModule deflate_module modules\/mod_deflate\.so/g' /usr/local/src/mod_pagespeed/etc/httpd/conf.d/pagespeed.conf

sed -i 's/ModPagespeedFileCachePath \"\/var\/www\/mod_pagespeed\/cache\/\"/ModPagespeedFileCachePath \"\/var\/mod_pagespeed\/cache\/\"/g' /usr/local/src/mod_pagespeed/etc/httpd/conf.d/pagespeed.conf

sed -i 's/ModPagespeedGeneratedFilePrefix \"\/var\/www\/mod_pagespeed\/files\/\"/ModPagespeedGeneratedFilePrefix \"\/var\/mod_pagespeed\/files\/\"/g' /usr/local/src/mod_pagespeed/etc/httpd/conf.d/pagespeed.conf


##copy the new pagespeed.conf to httpd##
cp /usr/local/src/mod_pagespeed/etc/httpd/conf.d/pagespeed.conf /usr/local/apache/conf/

##set directory permissions and create directories for files and cache##
chmod 755 /usr/local/apache/modules/mod_pagespeed.so
mkdir /var/mod_pagespeed/{cache,files} -p
chown nobody:nobody /var/mod_pagespeed/*

##restart httpd##
service httpd restart

##send mail to alert of update so that pagespeed.conf can be altered if necessary, can be checked against pagespeedbak.conf created during the update.##

SUBJECT="Mod Pagespeed has been updated"
EMAIL="someone@somewhere.com"
EMAILMESSAGE="/tmp/emailmessage.txt"
echo "Mod Pagespeed has been updated, check pagespeed.conf"> $EMAILMESSAGE
/bin/mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGE
rm /tmp/emailmessage.txt

##else if the rpm on google has not been updated then just say so##
else
echo Mod_Pagespeed Upgrade not required at this time!
fi




Obviously the SED section of the code would need to be altered depending on what configs are set in pagespeed.conf, the above example is what I require in mine.

Saturday, March 12, 2011

New Website HairBeautyMall.com

Latest website to compare prices of hair and beauty products from major retailers, both in UK & USA.

Discount vouchers, coupon codes and hair and beauty articles.

Artists portfolio website ...

This site has been built for an artist who wanted to be able to simply upload a folder of images and display them as projects on her website. Built using a heavily customised plogger script and php/mysql backend so that it can be fully edited by the artist whenever required.











Tuesday, January 04, 2011

2011 London Firework Display



The London new years fireworks are always spectacular, this year they were set to music for the first time and were amazing! HAPPY NEW YEAR!

Soundtrack

0:58 - 1:01 Club Foot - Kasabian
1:52 - 2:28 20th century boy - T-Rex
2:34 - 3:33 We Will Rock You - Queen
3:34 - 4:14 Pass Out - Tinie Tempah
4:15 - 4:33 Lucy In The Sky With Diamonds - The Beatles
4:34 - 5:10 You Got The Love - Candi Staton
5:11 - 6:00 London Calling - The Clash
6:04 - 6:56 Don't Stop Till You Get Enough - Bollywood Freaks
7:01 - 7:33 All Time Low - The Wanted
7:34 - 8:17 Song2 - Blur
8:18 - 9:52 Holiday - Dizzee Rascal

Wednesday, November 03, 2010

Mount Merapi Eruption 2010

Gunung Merapi (Mountain of Fire), is a volvano on the border between Java and Yogyakarta in Indonesia. It is one of the worlds most active volcanoes and stands at 2968 meters high (at the moment). It is currently again going thorugh a very active phase.

Mount Merapi is again erupting, people who live around and on Merapi have been evacuated as the volcano continues to cover the surrounding area with ash. Many peoples livelihoods depend on Merapi. Their livestock grazes on Merapi's slopes and many have bravely returned to care for their animals, despite the danger posed by the current eruption.



This is a video closeup using time lapse of the lava flow from Merapi in 2009...



I visited Merapi in the 1990's with a friend who was a climber. We climbed Merapi, led by a local guide, through the night, to be at the summit for sunrise on the Indonesian New Years Day. It was one of the most memorable things I have ever seen. It was a tough hike to the top and freezing cold, but the earth up there was hot and steaming. There was molten lava, steam vents and the curve of the earth was visible on the horizon, as was the blackness of space. We sat at the top wrapped in blankets, waiting for the sunrise. This is a picture of the view that I saw back then...

Monday, April 26, 2010

Impatient 4 Ubuntu

The days are seeming like years as I wait for Ubuntu 10.04 to be released. I could install an older version or a different distributution to do what I want to do I guess, but I set my heart on Ubuntu and getting the old release seems wrong when if I wait a few days I get the latest...and so I just have to wait..........

How come time actually slows down when waiting...I do not get how that happens?

Sunday, April 25, 2010

Latest Linux Ubuntu Release 10.04

The new version of the popular Linux distribution, Ubuntu, will be available soon in its final release form.

The latest Linux Ubuntu OS Release has the following improvements ...

GNOME
Ubuntu 10.04 LTS RC includes the latest GNOME desktop environment with a number of great new features.

Linux kernel 2.6.32
Ubuntu 10.04 LTS RC includes the 2.6.32-21.32 kernel based on 2.6.32.11.

KDE SC 4.4
Kubuntu 10.04 LTS RC features the new KDE SC 4.4. For more information about new features in Kubuntu, see the Kubuntu technical overview.

HAL removal
This release fully removes HAL from the boot process, making Ubuntu faster to boot and faster to resume from suspend.

Major new version of likewise-open
The likewise-open package, which provides Active Directory authentication and server support for Linux, has been updated to version 5.4. The package supports upgrades from both the officially supported versions 4.0 (Ubuntu 8.04 LTS) and 4.1 (Ubuntu 9.10), as well as the likewise-open5 packages from universe.


New default open source driver for nVidia hardware

The Nouveau video driver is now the default for nVidia hardware. This driver provides kernel mode setting, which will give improved resolution detection. This driver provides hardware accelerated 2D functionality, like the -nv driver it replaces. The nouveau driver is being actively developed upstream and we anticipate this will enable faster bug fixes for problems encountered.


Improved support for nVidia proprietary graphics drivers
Three different NVIDIA proprietary drivers are currently available: nvidia-current (190.53), nvidia-173, and nvidia-96. Thanks to a new alternatives system, it is now possible to install all three of these packages at the same time (although it is only possible to have one configured for use at a time).

Social from the Start
We now feature built-in integration with Twitter, identi.ca, Facebook, and other social networks with the MeMenu in the panel, which is built upon the Gwibber project, which has a completely new, more reliable backend built on top of desktopcouch. Gwibber now also supports a multi-column view for monitoring multiple feeds simultaneously.

New boot experience
Multiple changes to look, feel and speed of the boot experience have been included in the Ubuntu 10.04 LTS Release Candidate.

New Indicators
The notification area now features more consistent user experience and design for communication, session management, and many other tasks. See the application indicators page for information on this change.

New Themes
The desktop has been beautified with the addition of two brand new themes, Ambiance and Radiance. New wallpaper and icons are also included.

Ubuntu One File Syncing
Select any folder in your home directory for sync, pick from your existing contacts when sharing folders. An updated preferences application has been added, with more features.

Ubuntu One Music Store
Millions of songs are available for purchase from your Ubuntu desktop, integrated with the Rhythmbox Music Player and using Ubuntu One cloud storage for backup and easy sync.

New features for Ubuntu Enterprise Cloud (UEC)
The Ubuntu Enterprise Cloud installer has been vastly improved in order to support alternative installation topologies. UEC components are now automatically discovered and registered, including for complex topologies. Finally, UEC is now powered by Eucalyptus 1.6.2 codebase.

Wednesday, February 03, 2010