Happy New Code Year
Posted by John on 09-Jan-2012 at 00:40am
In case you have not heard, apart from being the end of the World (bollocks), 2012 is also Code Year. Code Year is an initiative by Codecademy with the following statement:
It seems to be popular with over 250,000 people already registered, including New York Mayor, Michael Bloomberg. I have signed up as well. I am not sure how in-depth the course will go, but it is definitely interesting and well worth supporting. The first instalment is being released today, so sign-up quick if you want to get started.
Make your New Year's resolution learning to code. Sign up on Code Year to get a new interactive programming lesson sent to you each week and you'll be building apps and web sites before you know it.
It seems to be popular with over 250,000 people already registered, including New York Mayor, Michael Bloomberg. I have signed up as well. I am not sure how in-depth the course will go, but it is definitely interesting and well worth supporting. The first instalment is being released today, so sign-up quick if you want to get started.
Merry Christmas
Posted by John on 23-Dec-2011 at 10:01am

Single cells, single cells,
See how they divide!
There was one on Christmas Day
But now they’ve multiplied
Single cells, single cells,
Nothing much to do!
But sit around in a petri dish
Dividing into two!
Source: Blogel Bloglovich Antiblog
PHP Convert URL to Link using REGEX
Posted by John on 08-Dec-2011 at 07:27am
This little script uses the PHP preg_replace function to check a string and convert any URLs that begin with HTTP, HTTPS, FTP or WWW into valid HTML hyperlinks.
index.php
index.php
<html>
<head>
<title>Convert URL to Link using REGEX</title>
<style>
body {
font-family: arial, verdana, helvetica, sans-serif;
font-size: 10pt;
color: #333333;
}
.url {
font-weight: bold;
color: #990000;
}
</style>
</head>
<body>
<?php
// DATA STRING
$description = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. http://www.proinfaucibus.com/ elit sit amet dapibus imperdiet, velit augue auctor tortor, sit amet imperdiet ftp://leojusto.com eu arcu. Nunc egestas, velit vitae dapibus dapibus, odio nibh porta tortor, www.vitaevenenatis.net augue est faucibus lorem. Integer dapibus nibh quis enim tempus lacinia http://lacinianibh.co.uk malesuada. Vivamus vel metus vel https://maurisgravida.ac.uk tortor rutrum pulvinar vel faucibus est.';
// DISPLAY UNFORMATTED STRING
echo '<h1>Original String</h1>'.$description.'<hr />';
// DEFINE FUNCTION createURL AND PASS DATA STRING
function createURL($string) {
// CONVERT ANY URLS THAT BEGIN WITH HTTP / HTTPS / FTP INTO HYPERLINKS
$string= preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a class=\"url\" href=\"$3\">$3</a>", $string);
// CONVERT ANY URLS THAT BEGIN WITH WWW INTO HYPERLINKS
$string= preg_replace("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a class=\"url\" href=\"http://$3\" >$3</a>", $string);
// RETURN FORMATTED STRING
return($string);
}
// ECHO FORMATTED STRING
echo '<h1>Formatted String</h1>'.createURL($description);
?>
</body>
</html>
VW Camper Van Tent
Posted by John on 06-Dec-2011 at 09:34am
I think this has to be the most awesome tent I have ever seen and currently has a massive £130 saving for the next few days

Source: IWOOT

Source: IWOOT
PHP MySQL Last User Login
Posted by John on 05-Dec-2011 at 06:00am
Those of you that read my blog regularly will know that much of what I post is either code that I have needed to write for a client, or interesting questions that I have seen asked on various forums. Today's snippet falls into the latter of those two categories. I recently saw someone ask how they could run a query to extract the record with the most recent login date and time. Now, I have seen this asked many times and it is not an especially difficult question to answer. The problem is that many responders to these threads post incorrect code and many times the asker does not bother to check before accepting the answer!!!
Lets say that I have a user table (tbluser) with 3 fields (userID, username, lastlogin) and I want to return the record with the most recent login date. Now, you can see from the data below that the record with userID = 2 has the most recent login date.

The MySQL table structure (including sample data)) for tbluser is:
A lot of the answers I have seen posted are something like this:
This will return the correct lastlogin date, but will incorrectly return the userID and username:

The correct way to do this is to use a MySQL subquery to select all the data for the row based on the MAX login date from the subquery:
The full code for the example (index.php) is below and will return the correct data for the last login
Lets say that I have a user table (tbluser) with 3 fields (userID, username, lastlogin) and I want to return the record with the most recent login date. Now, you can see from the data below that the record with userID = 2 has the most recent login date.
The MySQL table structure (including sample data)) for tbluser is:
--
-- Table structure for table `tbluser`
--
CREATE TABLE IF NOT EXISTS `tbluser` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`lastlogin` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`userID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
--
-- Dumping data for table `tbluser`
--
INSERT INTO `tbluser` (`userID`, `username`, `lastlogin`) VALUES
(1, 'test1', '2011-11-22 15:46:44'),
(2, 'test2', '2011-11-28 22:42:31'),
(3, 'test3', '2011-04-28 22:42:31'),
(4, 'test4', '2011-09-28 22:42:10'),
(5, 'test5', '2011-05-28 22:42:10');
A lot of the answers I have seen posted are something like this:
$sql = mysql_query("SELECT *, MAX(lastlogin) AS lastlogin FROM tbluser") or die(mysql_error());This will return the correct lastlogin date, but will incorrectly return the userID and username:
The correct way to do this is to use a MySQL subquery to select all the data for the row based on the MAX login date from the subquery:
$sql = mysql_query("SELECT * FROM tbluser WHERE lastlogin >= (SELECT MAX(lastlogin) FROM tbluser)") or die(mysql_error());The full code for the example (index.php) is below and will return the correct data for the last login
<?php
// SWITCH ON ERROR REPORTING
error_reporting(E_ALL);
// DATABASE CONNECTION
$dbHost = "localhost";
$dbUser = "USERNAME";
$dbPass = "PASSWORD";
$dbName = "DATABASE";
$db = mysql_connect($dbHost,$dbUser,$dbPass);
mysql_select_db($dbName,$db);
// SET UP HTML PAGE STRUCTURE AND CSS
echo '<html>
<head>
<title>Last User Login</title>
<style>
body {
font-family: arial, verdana, helvetica, sans-serif;
font-size: 10pt;
color: #33333;
}
label {
width: 100px;
font-weight: bold;
}
</style>
</head>
<body>';
// EXECUTE QUERY TO FIND USER RECORD WITH LLAST LOGIN
$sql = mysql_query("SELECT * FROM tbluser WHERE lastlogin >= (SELECT MAX(lastlogin) FROM tbluser)") or die(mysql_error());
// SET ARRAY FOR RETURNED RESULT
while($row = mysql_fetch_array($sql)) {
// DISPLAY USER DETAILS
echo '<h1>Last User Login</h1><hr />
<label>ID: </label>'.$row['userID'].'<br />
<label>Username: </label>'.$row['username'].'<br />
<label>Last Login: </label>'.$row['lastlogin'].'<hr />';
}
echo '</body>
</html>';
?>
Software Engineering Explained
Posted by John on 30-Nov-2011 at 03:52am
PHP Saving Interest Calculator
Posted by John on 30-Nov-2011 at 03:44am
I was recently looking at putting a little bit of money in a savings account but I wanted to know how much I would get back at the end of the fixed term before I invested. There was no functionality on the page I was on so I had to go to Google and search for a savings rate calculator. I found one at Money Supermarket that worked well, but I don't want to have to go back to that site everytime I need to calculate interest for a bond. Also, the Money Supermarket one calculates the Basic Tax Rate as 22% which is incorrect. The HM Revenue & Customs has this as 20% for 2011-12. Therefore, I decided to build my own little version which will allow me to enter my own tax rate to bypass this issue. Have a look and let me know what you think.
index.php
index.php
<?php
// SWITCH ON ERROR REPORTING
error_reporting(E_ALL);
// SET THE HTML PAGE STRUCTURE AND CSS
echo '<html>
<head>
<title>Savings Calculator</title>
<style>
body, table {
font-family: arial, verdana, helvetica, sans-serif;
font-size: 10pt;
color: #333333;
}
label {
width: 100px;
font-weight: bold;
}
td, th {
width: 120px;
text-align: right;
}
.td1 {
font-weight: bold;
text-align: left;
}
.td2 {
font-weight: bold;
}
.input1 {
width: 25px;
text-align: right;
}
.errormsg {
font-weight: bold;
color: #990000;
}
</style>
</head>
<body>';
// SET INITIAL VARIABLE VALUES
$deposit = '';
$period = '';
$rate = '';
// IF CALCULATOR FORM IS SUBMITTED
if(isset($_POST['submit'])) {
// GRAB THE POSTED VALUES INTO VARIABLES
$deposit = addslashes(strip_tags($_POST['deposit']));
$period = addslashes(strip_tags($_POST['period']));
$rate = addslashes(strip_tags($_POST['rate']));
$tax = 100 - addslashes(strip_tags($_POST['tax']));
// IF ANY OF THE FIELDS ARE EMPTY
if(empty($deposit) || empty($period) || empty($rate) || empty($tax)) {
// DISPLAY ERROR MESSAGE
echo '<div class="errormsg">Please complete all fields</div>';
// IF ANY OF THE FIELDS CONTAIN NON-NUMERIC VALUES
} elseif(!is_numeric($deposit) || !is_numeric($period) || !is_numeric($rate) || !is_numeric($tax)) {
// DISPLAY ERROR MESSAGE
echo '<div class="errormsg">Please enter numeric values only</div>';
// IF INVALID VALUES ENTERED
} elseif($deposit < 0 || $period < 0 || $rate < 0 || $tax < 0 || $tax > 100) {
echo '<div class="errormsg">Invalid value entered</div>';
// IF VALIDATION IS SUCCESSFUL
} else {
// SET VARIABLE TO BE USED FOR CALCULATING INTEREST
$deposit_tax = $deposit;
// DISPLAY THE INITIAL DEPOSIT
echo '<h1>Results</h1>
<table border=1>
<tr>
<th class="td1">Initial Deposit</th>
<th>£'.number_format($deposit, 2, '.', ',').'</th>
</tr>';
// LOOP THROUGH AND CALCULATE COMPOUND INTEREST FOR EACH PERIOD
for($i=1; $i<=$period; $i++) {
// CALCULATE COMPOUND INTEREST PER PERIOD
$interest_tax[$i] = ((($deposit_tax / 100) * $rate) / 100) * $tax;
// UPDATE INTIAL DEPOSIT WITH INTEREST CALCULATED
$deposit_tax = $deposit_tax + $interest_tax[$i];
// DISPLAY INTEREST PER PERIOD
echo '<tr>
<td class="td1">Y'.$i.':</td>
<td>£'.number_format($interest_tax[$i], 2, '.', ',').'</td>
</tr>';
}
// DISPLAY THE TOTAL INTEREST EARNED MINUS THE INITIAL DEPOSIT
echo '<tr>
<td class="td1">Total (Interest):</td>
<td class="td2">£'.number_format($deposit_tax - $deposit, 2, '.', ',').'</td>
</tr>';
// DISPLAY THE FINAL TOTAL SAVINGS INCLUDING INITIAL DEPOSIT
echo '<tr>
<td class="td1">Total (Savings):</td>
<td class="td2">£'.number_format($deposit_tax, 2, '.', ',').'</td>
</tr>
</table><br /><hr />';
// CLEAR FORM FIELD VARIABLES
$deposit = '';
$period = '';
$rate = '';
}
}
// INTEREST CALCULATOR FORM
echo '<h1>Calculator</h1>
<form action="index.php" method="post">
<label>Tax Rates: </label><input class="input1" type="text" name="tax" />% (e.g. 20)<br />
<label>Deposit: </label><input type="text" name="deposit" value="'.$deposit.'" /> (e.g. 1000)<br />
<label>Period (Years): </label><input type="text" name="period" value="'.$period.'" /> (e.g. 2)<br />
<label>Interest Rate: </label><input type="text" name="rate" value="'.$rate.'" /> (e.g. 4.5)<br />
<label></label><input type="submit" name="submit" value="Calculate" />
</form>
</body>
</html>';
?>
Wisdom of the Ancients
Posted by John on 29-Nov-2011 at 06:22am
MySQL Return Records Previous X Months
Posted by John on 29-Nov-2011 at 01:49am
I was recently asked to produce a report that would query the database and return all new account holders from the previous 3 months. To do this you need to use the MySQL date functions: DATE_SUB and CURDATE. Here is the example MySQL table structure with sample data and PHP code to execute the query.
tbluser
index.php
tbluser
--
-- Table structure for table `tbluser`
--
CREATE TABLE IF NOT EXISTS `tbluser` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`userID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6;
--
-- Dumping data for table `tbluser`
--
INSERT INTO `tbluser` (`userID`, `username`, `created`) VALUES
(1, 'test1', '2011-04-22 15:46:44'),
(2, 'test2', '2011-05-28 19:34:31'),
(3, 'test3', '2011-09-28 22:42:31'),
(4, 'test4', '2011-10-28 22:42:10'),
(5, 'test5', '2011-11-28 22:42:10');
index.php
<html>
<head>
<title>New Accounts</title>
<style>
body {
font-family: arial, verdana, helvetica, sans-serif;
font-size: 10pt;
color: #333333;
}
label {
width: 100px;
font-weight: bold;
}
</style>
</head>
<body>
<?php
// CONNECT TO DATABASE
$dbHost = "localhost";
$dbUser = "USERNAME";
$dbPass = "PASSWORD";
$dbName = "DATABASE";
$db = mysql_connect($dbHost,$dbUser,$dbPass);
mysql_select_db($dbName,$db);
// EXECUTE QUERY TO RETURN ONLY RECORDS OLDER THAN THE LAST 3 MONTHS
$sql = mysql_query("SELECT * FROM tbluser WHERE DATE_SUB(CURDATE(), INTERVAL 3 MONTH) < created") or die(mysql_error());
echo '<h1>Results</h1><hr />';
// LOOP THROUGH RESULTS
while($row = mysql_fetch_array($sql)) {
// DISPLAY ACCOUNT DETAILS
echo '<label>ID:</label>'.$row['userID'].'<br />
<label>Username:</label>'.$row['username'].'<br />
<label>Created:</label>'.date('d-m-Y H:i:s',strtotime($row['created'])).'<br /><hr />';
}
?>
</body>
</html>
PHP Regular Expressions Password Validation
Posted by John on 26-Nov-2011 at 23:35pm
Just a quick little PHP PCRE regular expression script to evalute a string. This is useful for validating passwords that need to comply with certain criteria.
index.php
index.php
<?php
// REPORT ALL ERRORS
error_reporting(E_ALL);
echo '<html>
<head>
<title></title>
</head>
<body>';
// IF PASSWORD FORM SUBMITTED
if(isset($_POST['submit'])) {
// GRAB POSTED PASSWORD VALUE INTO VARIABLE
$passw = $_POST['passw'];
// IF NO PASSWORD ENTERED
if(empty($passw)) {
// DISPLAY ERROR MESSAGE
echo 'Please enter password';
// ELSE IF PASSWORD DOES NOT MATCH CRITERIA
/*
------------------------------------------------------
"/^ - START OF THE STRING TO BE EVALUATED
------------------------------------------------------
(?=. - CHECK IF THE FOLLOWING REGEX...
{8,20}) - ...LENGTH IS BETWEEN 8 AND 20 CHARACTERS
------------------------------------------------------
(?=. - CHECK IF THE FOLLOWING REGEX...
* - ...CONTAINS ANY NUMBER OF...
[a-z]) - ...LOWERCASE CHARACTERS
------------------------------------------------------
(?=. - CHECK IF THE FOLLOWING REGEX...
* - ...CONTAINS ANY NUMBER OF...
[A-Z]) - ...UPPERCASE CHARACTERS
------------------------------------------------------
(?=. - CHECK IF THE FOLLOWING REGEX...
* - ...CONTAINS ANY NUMBER OF...
[0-9]) - NUMERIC CHARACTERS
------------------------------------------------------
.* - MATCH ANY NUMBER OF CHARACTERS
------------------------------------------------------
$/" - END OF THE STRING TO BE EVALUATED
------------------------------------------------------
*/
} elseif(!preg_match("/^(?=.{8,20})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$/", $passw)) {
// DISPLAY ERROR MESSAGE
echo 'Password does not match criteria';
// ELSE DISPLAY SUCCESS MESSAGE
} else {
echo 'Password was valid';
}
}
// PASSWORD FORM
echo '<form action="index.php" method="post">
Password: <input type="password" name="passw" /> (8-20 characters, must contain at least 1 uppercase, lowercase and numeric character)<br />
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>';
1 2 3 Next > Last »





