PHP: HTML Form 2 Email

Assuming you have a very basic form already set up, using a submit button will allow you to call a php script:

<form method="post" action="contact.php">
<input name="email" type="text">
<textarea name="message" rows="15" cols="40"></textarea>
<input type="submit">
</form>

You’ll obviously format your form as you see fit, adding as many fields as you need to achieve what your after. The important bit is the PHP code you’ll use in “contact.php” to process the input of the form.

<?php
$to = "you@yoursite.com";
$subject = "Contact Us";
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
$headers = "From: $email";
$sent = mail($to, $subject, $message, $headers) ;
if($sent)
{print "Your mail was sent successfully"; }
else
{print "We encountered an error sending your mail"; }
?>

$_REQUEST takes the variables from the form - the “name” of each form element will be the name of the variable passed. For example “email” and “message” are the variables taken from the script and are the names of the form elements.

All that happens after this is the script takes all the variables and passes them to the php mail function which generates and sends an email to the address at the top of the script.

Easy

SimpleLife 1.3 Release

Eventually….. I managed to fix the cache issues. Turns out 90% of them were caused by people who didn’t have a cache folder. Tsk. I spent 6 months trying to fix a problem that wasn’t there. :|

Anyway, started coding up relative dates and a date cut off today so that shouldn’t take long.

These aren’t features that I am that bothered about by the way, but they seem popular and I have been doing loads of PHP coding at work recently and am now looking at “problems” and seeing “solutions” without have to think, so its good practice.

PHP: Calculate Difference Between Dates As Strings

There are plenty of well documented methods to calculate the difference between two dates. However its not so easy when you don’t have a date type, but a string which represents a date. You could turn the string into a date, then do some math and come up with a difference but thats long winded!

The easiest method when you have a string such as “21/06/08″ is to work out what day of the year that is (between 0 and 365) and subtract one from the other.

This function uses the explode function to seperate the string into parts (you’ll see the first variable is ‘/’ which happens to be my delimiter in this case, you could use ‘-’ or something similar) and gregoriantojd which takes the month, day and year in that order to return the day number in that year.

$day1 = explode('/', $day1);
$day2 = explode('/', $day2);
$start_date=gregoriantojd($day1[1], $day1[0], $day1[2]);
$end_date=gregoriantojd($day2[1], $day2[0], $day2[2]);
$days = $end_date - $start_date;

So American formatted dates would need a switch in the variables of the gregoriantojd function to 0, 1 ,2 or M, D, Y as they usually show their months first.

Copying And Pasting Values Across Multiple Rows In A Filtered List In Microsoft Excel

That sounds like a complicated task in itself, without even considering how unhelpful MS Excel can be…. What exactly am I trying to achieve?! How frequently does this need occur?

I work with massive spreadhseets. Sure I should probably use a specific database application, but seeing as Access sucks balls and everybody in my company literally wants to marry Excel I have little choice in the matter… I run a couple of databases, the specifics of which are unimportant, which have around 30-40 thousand rows acting as records. I have the data set up with auto filters for the coloumn headers so that I can show data that matches specific criteria in each coloumn (show all rows where postcode starts “AB” for example) or order rows according to any specific coloumn (like sort rows in order of postcode).

The problem occurs when working on specific subsets of this data. Fow example, say I am working on all accounts within the AB postcodes, where there is no manager name. I can add a formula into the top cell, a vlookup for example, and autofill this formula to the bottom of the displayed rows. Excel intelligently only applies this formula to the visible cells which is great… the hidden rows between which have been excluded by the filter are unaffected, which makes sense.

Now, with 40,000 rows and 15 coloumns, my spreadsheet has 600,000 cells. Thats over half a million pieces of data to hold in relation to each other. Obviously Excel begins to labour - changing filter criteria can take a couple of seconds, even using the end key to navigate to the bottom of the data can take a couple of seconds where its normally instant.

This in itself is not an issue but the problem is compounded with formulas. Every time you change a filter, Excel works out which rows to show and then recalculates every formula in the sheet. The more formulae you have the longer it takes until eventually you’re waiting hours to show just one postcode.

Most people profficient or at least familiar with Excel formulas know copying and pasting the cells that contain formulas as values (eg Copy, Paste Special, Paste Values) cuts out this added complication.

But that isn’t that easy when working with filtered lists! Try and copy a selection of cells in a filtered list and then paste them back on top as values and you’ll more than likely get some errors. The problem stems from hidden rows between the rows you are copying/pasting. Excel fails miserably to ignore these hidden cells, and if it works at all it will almost certainly overwrite hidden data with the copied values, leave formulas in other rows and generally fuck about with your karma.

The obvious work around is to release all criteria on the filters (Data -> Filter -> Show All is the easiest method) and copy any coloumn affected by your newly added formulas and then immediately paste them as values. This effectively replaces all formulas in these ranges with their “answers” and leaves any formatting intact.

The problem is, when I’m repeating this process maybe 10 - 20 times a day it gets intensely frustrating. Once you’ve done this, you still need to reapply the criteria you had and in a big spreadsheet this whole workaround can take a couple of minutes as Auto Filter needs to recalculate its visible data and all the formulas you haven’t changed yet. These minutes soon add up!

So I’ve hit another solution - a very simple macro which I’ve currently got assigned to a toolbar button which gets more use than any other.

Public Sub Values()
Dim cell As Object

Selection.SpecialCells(xlCellTypeVisible).Select

For Each cell In Selection
cell.Value = cell.Value
Next cell

End Sub

Once I’ve copied the formula down (or across etc) I select the cells that contain formula in the usual way and then run the macro.

It first takes the selection and very quickly narrows the selection to only visible cells. This is the most important part because as discussed, any initial selection you make contains the hidden cells between the selected visible cells.

Lastly it cycles through each cell in this new narrowed selection and copies the value directly into the cell. So if the cell contained the formula =2+2, the macro will take the value 4 and reset the cell to that value. This works for any formula, however complex.

The result is the ability to copy formulas and paste their values into any selection of cells, whether the are filtered with Auto Filter or not. Its how Copy and Paste Values should work - in fact its how copy and paste should behave full stop, but thats a different less elegent problem.

Reading back through it all seems a bit over the top, but so far it saves me about half an hour a day which is about 120 hours a year (taking into account holidays!) - thats 3 and a half weeks of my working life I got back! If only I hadn’t just run out of things to do!!

Javascript - Numbers to Currency

So a small project recently saw me create (or more accurately complete) a web page to be shown on a large screen tv at work - the idea being the page would track daily install figures and show remaining targets etc.

The problem was the system took numbers from a static file, which was updated daily. The targets were preset and the remaining figures were calculated from these numbers. Obviously using commas and pound signs would mess up the math. I could strip the special characters first, but then I’d have to rebuild the totals with special formatting. If I was going to format the numbers at any point i might as well store them as flat integers and format them everytime i wanted to show them.

So this function takes any number, rounds it to 2 decimal places, inserts commas and adds a pound sign. Swish. To call it, wrap anything you want to display as money in the money function… eg

' + money(array[i]) +';

That was fun. I need to get out more.

<SCRIPT LANGUAGE="JavaScript">
<!-- Kieran Delaney -->
<!-- http://kierandelaney.net/blog -->
<!-- Begin
function money(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
pence = num%100;
num = Math.floor(num/100).toString();
if(pence<10)
pence = "0" + pence;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '£' + num + '.' + pence);
}
// End -->
</script>

Aligning Images With Wordpress

Its been a while since I geeked up. I’ve been working the equivelent of one and a half full time jobs, and accidently bought a playstation 3 so geekness (unless it involves burnout chains 8 long) has taken the back seat (see I’m so enraptured by Burnout Paradise on our 46″ HD screen that I’m even talking through driving analogies!)…

So yeah - Picturegrid and SimpleLife are still in development, I made some changes this morning in fact!

It occured to me that my book entries looked a bit ugly - book cover, dates and review. Simple and plain, but a bit naff…. What if I could align the book cover and have it float inside the text? It got me thinking about some other posts where the image is small enough to float inside a paragrah of text….

Turns out its easy, if you’re happy editing the css of your theme….

Firstly you have to set up the right and left “styles” - the margin and padding help keep everything tidy, whilst the display: inline tag makes the text flow around it.

img.right { padding: 4px; margin: 0 0 2px 7px; display: inline; }
img.left { padding: 4px; margin: 0 7px 2px 0; display: inline; }

You’ll also need to be using the following somewhere in your themes css….. now you could put the float tags inside the img.left/right styles but then they’d only be available for images aligned left and right. Set seperately, you’ll be able to quickly set anything to the left or right (although text won’t float around it).

.right { float: right; }
.left { float: left; }

So I guess there are plenty of examples now throughout my blog… all you need to do is insert the image tag with class=”left”.

<img src="animage.jpg" title="Yada" alt="Yada" class="left" />

Smoke Or FireFor example this image is floating on the right - i used class=”right” so that it floats lovely and inline with the text floating all around it. Its quite a simple little fix that improves the layout of a post dramatically, which I’ll probably use on nearly every image i post - obvious exceptions are big images, or special images or image which plain just don’t fit inside text.

SimpleLife Flickr Updates

Check out my lifestream for exciting developments on the SimpleLife front.

Coming soon:

  • Show Flickr images in feed. (Optional)
  • Show only Flickr photos in specific tag. (Optional)
  • Flickr related links to a non photo page are not marked in flickr colours. For example a link to a flickr set from delicious, will now look like a link from delicious instead of an uploaded photo.

Plugin Standards

Suggestions For Plugin Standards

Hmm… seems like I’ve got some work to do! I’m still struggling with uploading my plugins to wordpress.org - svn isn’t particularly user friendly for the unitiated, and my picturegrid plugin page currently looks like death. WHY?! EVERYTHINGS HOW IT SHOULD BE! Feel like banging my head against a wall, as there is literally nowhere to turn for help…

ICONIZE!

So I’ve written another wordpress plugin. Well, when i say “written” i really mean compiled, because this one is based on the rather excellent Iconize project created by Alexander Kaiser.

IconizeWP is a simple wordpress plugin that attempts to intergrate Alexander Kaiser’s excellent Iconize project with any Wordpress blog. Simply activate the plugin and all links will have an icon designating the target’s content. Icons by famfamfam.

Some examples of the plugin in action (Note - you’ll only see these in a supported browser!):

SimpleLife 1.1b

You wait all week for an update and two come along in minutes. Thanks to Kev who pointed out a nasty typo bug which caused 1.1a to run a PHP5 function in 4.x

No need to upgrade from 1.1a to 1.1b if you already have 1.1a and it wrs (ie you’re using PHP5).

Powered by WordPress with GimpStyle Theme heavily modified by Kieran Delaney.
Entries and comments feeds. Valid XHTML and CSS. 20,414 spam comments ignored.