Thursday, December 01, 2011

Gwalior Childrens Charity Award For Volunteering

I manage the website for the GCC at http://www.helpchildrenofindia.org . This is a picture of me receiving an award from Dr B.K.Sharma. He and his late wife Meena are founders of the charity that has rescued many destitute children from various state run institutions. When his wife passed, her estate was used to build a home, hospital and school in Gwalior, Madhya Pradesh (one of the poorest and most deprived parts of India) The charity provides for the residents there and is working to become self sufficient with solar power, a Goshala, and farming area. As well as helping the disabled and destitute, the place also helps local people, especially girls from surrounding villages, providing them with a free education at the new school that opened this year. They also provide a mobile medical center that travels offering medical assistance in the surrounding area.

Wednesday, October 26, 2011

Currency database - csv with currency symbol html codes

I couldnt find a currencies data file anywhere to import into a database. I wanted the currency name, abbreviation and the html code for the currency symbol, to use in select menus and such.

So I made a csv using the data from XE.com. That took a little time using regex to find and replace the table data and as it took a little time I thought I would share the file here for anyone else who may need currency data with html symbols for website use.

This is the csv data that can be copied and pasted into a file to import into a database table..

Albania Lek--ALL--Lek | Afghanistan Afghani--AFN--؋ | Argentina Peso--ARS--$ | Aruba Guilder--AWG--ƒ | Australia Dollar--AUD--$ | Azerbaijan New Manat--AZN--ман | Bahamas Dollar--BSD--$ | Barbados Dollar--BBD--$ | Belarus Ruble--BYR--p. | Belize Dollar--BZD--BZ$ | Bermuda Dollar--BMD--$ | Bolivia Boliviano--BOB--$b | Bosnia and Herzegovina Convertible Marka--BAM--KM | Botswana Pula--BWP--P | Bulgaria Lev--BGN--лв | Brazil Real--BRL--R$ | Brunei Darussalam Dollar--BND--$ | Cambodia Riel--KHR--៛ | Canada Dollar--CAD--$ | Cayman Islands Dollar--KYD--$ | Chile Peso--CLP--$ | China Yuan Renminbi--CNY--¥ | Colombia Peso--COP--$ | Costa Rica Colon--CRC--₡ | Croatia Kuna--HRK--kn | Cuba Peso--CUP--₱ | Czech Republic Koruna--CZK--Kč | Denmark Krone--DKK--kr | Dominican Republic Peso--DOP--RD$ | East Caribbean Dollar--XCD--$ | Egypt Pound--EGP--£ | El Salvador Colon--SVC--$ | Estonia Kroon--EEK--kr | Euro Member Countries--EUR--€ | Falkland Islands (Malvinas) Pound--FKP--£ | Fiji Dollar--FJD--$ | Ghana Cedis--GHC--¢ | Gibraltar Pound--GIP--£ | Guatemala Quetzal--GTQ--Q | Guernsey Pound--GGP--£ | Guyana Dollar--GYD--$ | Honduras Lempira--HNL--L | Hong Kong Dollar--HKD--$ | Hungary Forint--HUF--Ft | Iceland Krona--ISK--kr | India Rupee--INR--₹ | Indonesia Rupiah--IDR--Rp | Iran Rial--IRR--﷼ | Isle of Man Pound--IMP--£ | Israel Shekel--ILS--₪ | Jamaica Dollar--JMD--J$ | Japan Yen--JPY--¥ | Jersey Pound--JEP--£ | Kazakhstan Tenge--KZT--лв | Korea (North) Won--KPW--₩ | Korea (South) Won--KRW--₩ | Kyrgyzstan Som--KGS--лв | Laos Kip--LAK--₭ | Latvia Lat--LVL--Ls | Lebanon Pound--LBP--£ | Liberia Dollar--LRD--$ | Lithuania Litas--LTL--Lt | Macedonia Denar--MKD--ден | Malaysia Ringgit--MYR--RM | Mauritius Rupee--MUR--₨ | Mexico Peso--MXN--$ | Mongolia Tughrik--MNT--₮ | Mozambique Metical--MZN--MT | Namibia Dollar--NAD--$ | Nepal Rupee--NPR--₨ | Netherlands Antilles Guilder--ANG--ƒ | New Zealand Dollar--NZD--$ | Nicaragua Cordoba--NIO--C$ | Nigeria Naira--NGN--₦ | Korea (North) Won--KPW--₩ | Norway Krone--NOK--kr | Oman Rial--OMR--﷼ | Pakistan Rupee--PKR--₨ | Panama Balboa--PAB--B/. | Paraguay Guarani--PYG--Gs | Peru Nuevo Sol--PEN--S/. | Philippines Peso--PHP--₱ | Poland Zloty--PLN--zł | Qatar Riyal--QAR--﷼ | Romania New Leu--RON--lei | Russia Ruble--RUB--руб | Saint Helena Pound--SHP--£ | Saudi Arabia Riyal--SAR--﷼ | Serbia Dinar--RSD--Дин. | Seychelles Rupee--SCR--₨ | Singapore Dollar--SGD--$ | Solomon Islands Dollar--SBD--$ | Somalia Shilling--SOS--S | South Africa Rand--ZAR--R | Korea (South) Won--KRW--₩ | Sri Lanka Rupee--LKR--₨ | Sweden Krona--SEK--kr | Switzerland Franc--CHF--CHF | Suriname Dollar--SRD--$ | Syria Pound--SYP--£ | Taiwan New Dollar--TWD--NT$ | Thailand Baht--THB--฿ | Trinidad and Tobago Dollar--TTD--TT$ | Turkey Lira--TRY--TL | Turkey Lira--TRL--₤ | Tuvalu Dollar--TVD--$ | Ukraine Hryvna--UAH--₴ | United Kingdom Pound--GBP--£ | United States Dollar--USD--$ | Uruguay Peso--UYU--$U | Uzbekistan Som--UZS--лв | Venezuela Bolivar Fuerte--VEF--Bs | Viet Nam Dong--VND--₫ | Yemen Rial--YER--﷼ | Zimbabwe Dollar--ZWD--Z$




I created a mysql table with 4 columns, id,name,abb,html and then loaded the above data in phpmyadmin using the following mysql

LOAD DATA LOCAL INFILE '/path/to/currencies/file.txt' INTO TABLE `currency` FIELDS TERMINATED BY '--' ESCAPED BY '\\' LINES TERMINATED BY ' | '(
`name` , `abb` , `html`
)






This is the currency data that is contained, and how the html codes display...


Albania Lek - ALL - Lek
Afghanistan Afghani - AFN - ؋
Argentina Peso - ARS - $
Aruba Guilder - AWG - ƒ
Australia Dollar - AUD - $
Azerbaijan New Manat - AZN - ман
Bahamas Dollar - BSD - $
Barbados Dollar - BBD - $
Belarus Ruble - BYR - p.
Belize Dollar - BZD - BZ$
Bermuda Dollar - BMD - $
Bolivia Boliviano - BOB - $b
Bosnia and Herzegovina Convertible Marka - BAM - KM
Botswana Pula - BWP - P
Bulgaria Lev - BGN - лв
Brazil Real - BRL - R$
Brunei Darussalam Dollar - BND - $
Cambodia Riel - KHR - ៛
Canada Dollar - CAD - $
Cayman Islands Dollar - KYD - $
Chile Peso - CLP - $
China Yuan Renminbi - CNY - ¥
Colombia Peso - COP - $
Costa Rica Colon - CRC - ₡
Croatia Kuna - HRK - kn
Cuba Peso - CUP - ₱
Czech Republic Koruna - CZK - Kč
Denmark Krone - DKK - kr
Dominican Republic Peso - DOP - RD$
East Caribbean Dollar - XCD - $
Egypt Pound - EGP - £
El Salvador Colon - SVC - $
Estonia Kroon - EEK - kr
Euro Member Countries - EUR - €
Falkland Islands (Malvinas) Pound - FKP - £
Fiji Dollar - FJD - $
Ghana Cedis - GHC - ¢
Gibraltar Pound - GIP - £
Guatemala Quetzal - GTQ - Q
Guernsey Pound - GGP - £
Guyana Dollar - GYD - $
Honduras Lempira - HNL - L
Hong Kong Dollar - HKD - $
Hungary Forint - HUF - Ft
Iceland Krona - ISK - kr
India Rupee - INR - ₹
Indonesia Rupiah - IDR - Rp
Iran Rial - IRR - ﷼
Isle of Man Pound - IMP - £
Israel Shekel - ILS - ₪
Jamaica Dollar - JMD - J$
Japan Yen - JPY - ¥
Jersey Pound - JEP - £
Kazakhstan Tenge - KZT - лв
Korea (North) Won - KPW - ₩
Korea (South) Won - KRW - ₩
Kyrgyzstan Som - KGS - лв
Laos Kip - LAK - ₭
Latvia Lat - LVL - Ls
Lebanon Pound - LBP - £
Liberia Dollar - LRD - $
Lithuania Litas - LTL - Lt
Macedonia Denar - MKD - ден
Malaysia Ringgit - MYR - RM
Mauritius Rupee - MUR - ₨
Mexico Peso - MXN - $
Mongolia Tughrik - MNT - ₮
Mozambique Metical - MZN - MT
Namibia Dollar - NAD - $
Nepal Rupee - NPR - ₨
Netherlands Antilles Guilder - ANG - ƒ
New Zealand Dollar - NZD - $
Nicaragua Cordoba - NIO - C$
Nigeria Naira - NGN - ₦
Korea (North) Won - KPW - ₩
Norway Krone - NOK - kr
Oman Rial - OMR - ﷼
Pakistan Rupee - PKR - ₨
Panama Balboa - PAB - B/.
Paraguay Guarani - PYG - Gs
Peru Nuevo Sol - PEN - S/.
Philippines Peso - PHP - ₱
Poland Zloty - PLN - zł
Qatar Riyal - QAR - ﷼
Romania New Leu - RON - lei
Russia Ruble - RUB - руб
Saint Helena Pound - SHP - £
Saudi Arabia Riyal - SAR - ﷼
Serbia Dinar - RSD - Дин.
Seychelles Rupee - SCR - ₨
Singapore Dollar - SGD - $
Solomon Islands Dollar - SBD - $
Somalia Shilling - SOS - S
South Africa Rand - ZAR - R
Korea (South) Won - KRW - ₩
Sri Lanka Rupee - LKR - ₨
Sweden Krona - SEK - kr
Switzerland Franc - CHF - CHF
Suriname Dollar - SRD - $
Syria Pound - SYP - £
Taiwan New Dollar - TWD - NT$
Thailand Baht - THB - ฿
Trinidad and Tobago Dollar - TTD - TT$
Turkey Lira - TRY - TL
Turkey Lira - TRL - ₤
Tuvalu Dollar - TVD - $
Ukraine Hryvna - UAH - ₴
United Kingdom Pound - GBP - £
United States Dollar - USD - $
Uruguay Peso - UYU - $U
Uzbekistan Som - UZS - лв
Venezuela Bolivar Fuerte - VEF - Bs
Viet Nam Dong - VND - ₫
Yemen Rial - YER - ﷼
Zimbabwe Dollar - ZWD - Z$

Monday, October 24, 2011

PHP - function to search an associative array

To find the value of part of an associative array such as the one below, the function below will search for a term within the key that is specified in the function...

$arr = "Array ( [0] => Array ( [id] => 1 [date] => 2011-10-18 [details] => Shopping ) [1] => Array ( [id] => 2 [date] => 2011-10-01 [details] => Tax ) [2] => Array ( [id] => 123 [date] => 2011-10-18 [details] => Petrol )";



function getKeys($arr,$search){
foreach($arr as $keys=>$values)
{
foreach ($values as $key => $value) {
if($key=="date" && $value==$search){//$key=="date" can be any key from the array
$getkeys.=$keys.",";
}
}
}
$len=strlen($getkeys)-1; //get the length of $getkeys
$getkeys=substr($getkeys,0,$len); //remove the last comma
$getkeys=$pieces = explode(",", $getkeys); //make an arrayof the keys
return $getkeys;
}//end function getKeys

$getkeys=getKeys($arr,"2011-10-18");//search term can be anything, here it is a date
print_r($getkeys);//print the array


This will return an array of the keys of the elements of the array in which the search term was found. In this case Array ( [0] => 0 [1] => 2 )

Monday, October 17, 2011

MySQL resultset as an associative array

To save time and resources, when a php application is going to require the same resultset often, the resultset can be saved in a session as an associative array. Then when required in the script the saved session data can be referenced instead of querying the database again.

To return a resultset as an array named $ac_arr requires the following mysql...

$result=mysql_query("SELECT name,startdate,enddate FROM accounts") or die(mysql_error());

while(($ac_arr[] = mysql_fetch_assoc($result)) || array_pop($ac_arr));

The array_pop() function simply removes the extra element that would otherwise be appended to the array.

This can then be stored in a session variable and later referenced without re-querying the database...


$_SESSION['ac_array']=$ac_arr;

To list the keys and values of elements in the array

<?php
$acs=$_SESSION['ac_array'];
foreach($acs as $keys=>$values)
{
foreach ($values as $key => $value) {
echo $keys." : ".$key.":".$value."<br />";
}
}
?>

The above will display a list like this
0 : name : AC1
0 : startdate : 2011-08-16
0 : enddate : 2011-12-16
1 : name : AC2
1 : startdate : 2014-07-25
1 : enddate : 2024-07-25
2 : name : AC3
2 : startdate : 2012-05-10
2 : enddate : 2022-05-10

so you can reference any element in the array by calling
$acs[0][name] (will return AC1)
$acs[2][startdate] (will return 2012-05-10)

Sunday, October 16, 2011

Amino Acids In protein - Complementary protein sources

When eating a vegetarian diet, it is important to get the protein right.

Usually the protein content of various food is labelled in grams, but not all protein is equal. The combination of amino acids that make up the protein does matter.

For example, a person could get (for example) 10g protein from 100g wholewheat bread. However the human body would be unable to utilise all that protein, as wheat protein does not contain all the essential amino acids (the amino acids that the body has to be fed, as it can not make them itself). A food that contains all the essential amino acids is called a "complete protein". Vegetarian sources are dairy products, quinoa, soya. A food that contains protein but not all the essential amino acids is called an incomplete protein. An incomplete protein has some amino acids that limit it, these are called "limiting amino acids". In wheat (and most grain) protein for example, the limiting amino acid is lysine. As the body uses amino acids together to do stuff, in a ratio, it can therefor only process as much protein as the limiting amino acid allows.

So that is why it is necessary to complement vegetarian protein sources sometimes. For example mixing wheat or rice protein, with a legume protein (rice and dal, beans on toast, tortilla and refreid beans), results in all essential amino acids being present. As although wheat and rice lack lysine,it has plenty of methionine and tryptophan. Legumes are high in lysine, but low in methionine and tryptophan. Together they form a complementary protein.

I found a good utility online to check the amino acid profile of foods (from the USDA database)
Amino Acid Check

This can help to choose a variety of foods over a course of a day that will complement each other, so providing enough of all the essential amino acids.

I was surprised to see that most green vegetables, spinach, broccoli etc, in fact have excellent amino acid profiles, with all the essential amino acids contained. Obviously you would have to eat alot of greens to get the rda of protein, but I have read that our ancestors, in paleolithic times, might have eaten several carrier bag fulls of green leafy veg a day.

An interesting fact for weight watchers, is that 600g of broccoli, contains nearly 20g protein and under 150 calories. Weight watchers usually like to eat food that keeps them nice and full up without having too many cals. The equivalent calorie amount of rice, would be just around 35g, and would only provide about 3g protein. If hungry, I know which choice i would go for to keep me full for longer!

As a side note, recent reports state that eating broccoli along with something spicy such as mustard or horseradish, boosts it anto cancer properties. Vegetables have so many wonderful properties, that are only just being discovered.

I once used the USDA database to analyse my daily food intake and discovered that by eating 5 portions of fruit and veg a day, I was not achieveing the rda of all the nutrients. In fact to do so a person has to eat a really wide range of fruit and veg and in quite large quantities. Americas 7 a day advice is better, but still, it depends on what you choose. It is a complicated science really.

This post is about amino acids in protein though, it is a huge subject, but really important for vegetarians to get to grips with, as amino acids are the building blocks of life. Every part of the human bodily system requires amino acids to function and renew. From blood, skin and cartilage, to muscles and bones, hormones and enzymes. It is all very well taking a multi vitamin, but without amino acids, the vitamins and minerals will have nothing to act with.

Personally as a vegetarian for many years, I now have a couple of scoops of whey protein powder daily, to be certain that my body always has a good supply of these treasures. It also saves me having to think too much about combining other protein sources and I do like to keep my life simple!




Essential Amino Acids Important Functions In The Body:


Isoleucine (Ile) - for muscle production, maintenance and recovery after workout. Involved in hemoglobin formation, blood sugar levels, blood clot formation and energy.
Leucine (Leu) - growth hormone production, tissue production and repair, prevents muscle wasting, used in treating conditions such as Parkinson’s disease.
Lysine (Lys) - calcium absorption, bone development, nitrogen maintenance, tissue repair, hormone production, antibody production.
Methionine (Met) - fat emulsification, digestion, antioxidant (cancer prevention), arterial plaque prevention (heart health), and heavy metal removal.
Phenylalanine (Phe) - tyrosine synthesis and the neurochemicals dopamine and norepinephrine. Supports learning and memory, brain processes and mood elevation.
Threonine (Thr) monitors bodily proteins for maintaining or recycling processes.
Tryptophan (Trp) - niacin production, serotonin production, pain management, sleep and mood regulation.
Valine (Val) helps muscle production, recovery, energy, endurance; balances nitrogen levels; used in treatment of alcohol related brain damage.
Histidine (His) - the 'growth amino' essential for young children. Lack of histidine is associated with impaired speech and growth. Abundant in spirulina, seaweed, sesame, soy, rice and legumes.

cite

Wednesday, October 12, 2011

PHP - Get the last day of a month


<?php
function GetLastDayofMonth($year, $month) {
for ($day=31; $day>=28; $day--) {
if (checkdate($month, $day, $year)) {
return $day;
}
}
}
?>


Then to call the last day of the month

$lastdayofmonth = GetLastDayofMonth(2011, 02);
echo $lastdayofmonth;


This would print the last day of the month of February 2011

The function is in the notes for the checkdate php function at
http://php.net/manual/en/function.checkdate.php

Thursday, September 08, 2011

Jquery - submit form without page refresh and show php processed results

THE JQUERY
$(document).ready(function(){
$(".button").click(function() {
$.post("thephp.php", $("#saywhatform").serialize() ,
function(data) {
$('#results').html("Data Loaded: " + data);
});
return false;
});
});

THE HTML
<form id="saywhatform" action="">
<input type="text" name="something">
<a href=""><span class="button">Click Here</span></a>
</form>
<div id="results"></div>

THE PHP
$form_entry=$_POST['something'];
echo "You entered".$form_entry.";


So this code will allow a form to be submitted without a page refresh, the results processed by a php script and any results from the php can be printed put in a div on the page.

Monday, September 05, 2011

Jquery Datepicker - change Min Max dates on change of select box to values retrieved from mysql db

Using jquery datepicker, it is possible to restrict the date range available for selection
http://jqueryui.com/demos/datepicker/#min-max

I wanted the min and max dates to be dynamic variables based on mysql query results, that would change depending which value was selected in a select drop down.

To do this I created a php file that took the select drop down value and queried the database to return dates relevant to that value. Then outside the php tags, I put a javascript function, echoing the php variables as min max dates in two functions that could be called later using getscript().

Then all that is required is in the page where the datepicker is displayed, in the head section use .getscript() to get the variable jquery/javascript functions and apply them to various events, such as document.ready and .change of the select box value.

(The values of the select box are got using http://www.texotela.co.uk/code/jquery/select/ and passed as parameters on the url to the php script, where they are retrieved using $_GET['account'])

nb. The date needs to be correctly formatted, which can be done in the php code after retrieval from the db. The format of the date that is in the javascript function is like this:
YYYY, mm -1, dd
eg: 2011,01 -1 ,01



<script>
$(document).ready(function() {

var account = $("#accountselect").selectedValues();
$.getScript("restrictdates.php?account="+account+"", function() {minMax(); });


$('#accountselect').change(function() {
var account = $("#accountselect").selectedValues();
$.getScript("restrictdates.php?account="+account+"", function() {updateDate(); });
});

});

</script>

<select id="accountselect">
<option value="ac1">ac1</option>
<option value="ac1">ac1</option>
</select>

<input id="datepicker" type="text">



The restrictdates.php file is as follows...


<?php
$account=$_GET['account'];
//some php code here to retrieve specific $min and $max dates from database, for the relevant account
?>
function minMax() {
$("#datepicker" ).datepicker({
minDate: new Date(<?php echo $min; ?> ),
maxDate: new Date(<?php echo $max; ?>)
});
}

function updateDate() {
$( "#datepicker").datepicker('change',{
minDate: new Date(<?php echo $min; ?> ),
maxDate: new Date(<?php echo $max; ?>)
});
}


Tuesday, July 26, 2011

PHP - Is it a leap year?

After spending 20 minutes writing a short function to test a date to see if it is a leap year, I find that php has a built in date function to do the job. Never mind it was interesting anyway to discover that there is a method in the madness of leap years. According to wikipedia, if a year is divisible by 4 it is a leap year. But not if it is divisible by 100, unless it is divisible by 400....get it?

So this was my waste of time leap year calculating function..


<?php
$year = date('Y') ;
if ( $year %400 == 0 ) { $isleap = 'yes' ; }
elseif ( $year %100 == 0 ) { $isleap = 'no' ; }
elseif ( $year %4 == 0 ) { $isleap = 'yes' ; }
else {$isleap='no';}
if ( $isleap == 'yes')
{echo $year." is a leap year";}
else
{echo $year." is not a leap year";}
?>


The smart way to do it though is just with date('L'), this php function returns 1 if it is a leap year and 0 if it is not...much simpler...


<?php
$year=date('Y');
$isleap = date('L') ;
if ( $isleap == '1')
{echo $year." is a leap year";}
else
{echo $year." is not a leap year";}
?>

Tuesday, July 19, 2011

mysql compare two large tables - find records only in 1 table - for sitemap last modified date

I needed to compare two large tables each having over 2 million records and find the records that are in table 1 but not in table 2.

I only wanted the records from table 1 and not all records that were different from both tables, so on each select query I added a temporary column that stated which table the result was from, so that after the insert select, those with table2 in the temp column could be deleted, leaving just the table 1 records...which are new records that have been added to a database since the last update.

The UNION results are inserted into a new table, so that after being inserted, all records from table2 can be deleted...


INSERT INTO products_new (name,merchantid,tab)
SELECT MIN( name ) AS name, merchantid, tab
FROM (
SELECT name, merchantid, 'table1' AS tab
FROM products_import AS alias1
UNION ALL SELECT name, merchantid, 'table2' AS tab
FROM products_bak AS alias2
)AS alias_table
GROUP BY name
HAVING COUNT( name ) =1
ORDER BY name

So after populating the new products table, the records that were only in table 2 can be deleted, leaving a table with the unique values from table 1.


DELETE FROM products_new WHERE tab='table2'

I have used this in order to be able to make my sitemaps last modified date more accurate, as currently at each product update, all dynamically created product pages have a recent last modified date, even if they were previously present in the DB. Using this method, the last modified date of new products can be accurately shown as new pages, by accessing this new table.

Increase size of tmpDSK cPanel

The default temp partion size in cpanel is 512mb which is usually not enough and creates errors such as "Drive Critical: /usr/tmpDSK (/tmp) is 99% full".

It can be increased as follows using the following commands....


stop services, mysql,apache and cpanel
root@server [~]# /etc/init.d/mysql stop
root@server [~]# /etc/init.d/httpd stop
root@server [~]# /etc/init.d/cpanel stop

backup the /tmp folder
root@server [~]# cp -rfp /tmp /tmp_backup

lazy unmount of /tmp
root@server [~]# umount -l /tmp

remove tmpDSK
root@server [~]# rm -rf /usr/tmpDSK

edit securetmp script, find my $tmpdsksize = 512000; # Must be larger than 250000
increase to necessary for example 2gb my $tmpdsksize = 2072000;
root@server [~]# nano /scripts/securetmp

run securetmp script to recreate /tmp (tmpDSK) partition at size specified
root@server [~]# /scripts/securetmp

Monday, July 11, 2011

Bash - loop through files updated in last 7 days

From command line or in a bash script, to loop thorugh all files that have been updated in the last however many days (in this example 7)...use the FIND command...


FILES=$(find /path/to/directory/ -type f -mtime -7)
for f in $FILES
do

echo $f

done

Saturday, July 09, 2011

php to display mysql query results in html table


The following code would go in an html document (that is able to display php) and display dynamic results from a mysql table into the table. This example builds a table that is 3 columns width, so the code to write the table is based on the number of rows returned from the mysql result, adding extra empty cells at the end if required.

A screen shot below, shows how the numbers are counted through to write the necessary html code to display the mysql results. In this example 19 rows are returned from mysql, so two extra table cells were required at the end, as 7 rows of 3 cells is 21 cells required. The table cells broke with a row after every count of 3.




<!-- open the table tags in the html document -->
<table border="1px"><tr>


<?php

//select the columns required from the mysql table
$result=mysql_query("SELECT name,description FROM gifts ORDER BY name");

//get count of rows returned
$numrows=mysql_num_rows($result);

//for a table with 3 columns divide the number of results by 3 and round up
$numtr=ceil($numrows/3);

//get the remainder
$remainder=$numrows % 3;
//from that calculate how many extra table cells are required in the final row
$xtratd=3-$remainder;


$i=1;//count for <td>
$x=1;//count for <tr>

//loop through $result declaring variables for any result required to go in the table
while($row=mysql_fetch_array($result))
{
$catname=$row['name'];
$catdesc=$row['description'];

//for demo purposes the values of $x and $i are shown in the table cells here
echo "<td>&#36;i is ".$i."<br />&#36;x is ".$x."<br /></td>";

//this line starts and end a new row in the table and increments the count of table rows (tr)
if(($i % 3 == 0) && ($x!=$numtr)){echo "</tr><tr>";$x++;}

//if the total number of rows is reached get how many extra table cells are needed and write them, then close the final row
if($i==$numrows)
{
for($z=1;$z<=$xtratd;$z++){
echo "<td>&#36;xtratd is ".$z."</td>";
}
echo "</tr>";
}

$i++;//increment the count of table cells (td)
}

?>

<!-- close the table tags in the html document -->
</table>



MYSQL - Update one columns data from another table

To copy one columns data to another existing tables column in mysql, it is possible with an update query like this :

UPDATE table1,table2
SET table1.coltocopy=table2.coltocopy

WHERE table1.coltocompare=table2.coltocompare;

Tuesday, July 05, 2011

PHP - Limit A Loop - FOREACH,WHILE etc

If you just want to loop through (for example) 2 iterations of a loop, rather than returning the whole set of data, you can insert a break clause to limit the number of times the data is looped through and so limit the results to two iterations.

$i = 0;

foreach($vars as $var){

//code to run


if(++$i > 2) break;

}

Monday, June 27, 2011

PHP - Assign variable names to array elements from mysql query

It is useful to be able to take the results of a MYSQL query and assign variable names to the results, so that they can be used later on in a script.

This can be done simply as follows...


$result= mysql_query("SELECT id FROM table WHERE num='567' LIMIT 3") or die(mysql_error());

while ($row = mysql_fetch_array($result)) {

$ids[] = $row['id'];

}
$id1 = $ids[0];
$id2 = $ids[1]
$id3 = $ids[2];


So you now have 3 variables fetched from the mysql array that can be used outside of a loop.

This specific example limits the mysql result to 3. However you could do this for any (change the 3 to how many results you want) and unknown numbers of results doing a COUNT of returned results and then iterating based on that number.

Monday, June 20, 2011

Price Comparison Site Relaunched

findallsorts price comparison site
FindAllSorts.com and FindAllSorts.co.uk were relaunched this week.

FindAllSorts has been split across two domains, one for the UK price comparisons and one for the USA price comparisons.

The site has been rebuilt and improved in both functionality and design. New features are available, the search is better, with the ability to filter product search results so users can be more specific as to what brands or stores or price they wish to check.

There is also a discount vouchers section, where all the online stores discount vouchers are shown and searchable. all coupon codes and special offers are updated daily with details of how long the offer or code will be valid for. So when buying a product it is a good place to check to see if a discount may be available.

UK Price Comparison Site - Find and compare prices of products in the UK. Find discount vouchers, coupon codes and special offers to get yourself the best deal.

USA Price Comparison Site - Find and compare prices of products in the USA. Find discount vouchers, coupon codes and special offers, to get yourself the best deal.

Amazon and Ebay products will also soon be included.

Compare prices to find the best deals at FindAllSorts!

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