Monday, 8 December 2008

upgrading to php 5 with Heart Internet

create a .htaccess file with the line:


Tuesday, 2 September 2008

Deleting unwanted images of the server.

What I wanted to do was to write a script that after loading an image would then check the image folder for any unwanted image, which would then be deleted.

So first of all I wanted to get a list of files in the folder - for this we need to use readdir - see

function list_folder($folder){

$dh = opendir($folder);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
return $files;



//Then i needed to make an array of a list of images that I do want to keep.

//my list looks a bit like this

$images_wanted_array[0] = $row['img1'];
$images_wanted_array[1] = 'thum'.$row['img1'];

/* once have these two list then I run a foreach inside a foreach statement.
So each file gets checked against the list of wanted files. If theres a match I get the result '$success'. After checking the whole wanted list I do a check for any succesful matches and only delete if there aren't any.
Here's the function I wrote.

function deleting_unwanted_images($images_array, $wanted_array, $path){ // this function takes an array of images and they aren't on the wanted_array list they will be deleted.

foreach ($images_array as $f) {
foreach ($wanted_array as $i){
if ($f == $i){
$success = TRUE;
if (!$success){
$file_to_delete = $path.$f;
echo '
The file'.$f.' - has been deleted
}else {
echo '
There has been a match so we are going to keep the file '.$f.'


Monday, 1 September 2008

importing a database .csv to mysql

** this post also included a solution for Invalid query: Duplicate entry '127' for key errors **

The mission -> I have databases given to me in .csv format created in Microsoft Excel and I would like to import them into my mysql database so I can manipulate them from there.

The Solution -> the key to writing the solution for this can be found by using .

here's the code I wrote from this page. You will need to create your table first that we write to.


$row = 1;
$handle = fopen ("database.csv","r");
// ip-to-country.csv must be in the same directory with this php file
// customer number here will represent the row it's on database given.

while ($data = fgetcsv ($handle, 1000, ",")) {
$query = "INSERT INTO database_table(`id`, `field1`, `field2`, `field3`)

VALUES('', '".$data[0]."', '".$data[1]."', '".$data[2]."')";
$result = mysql_query($query) or die("Invalid query: " . mysql_error().__LINE__.__FILE__);
fclose ($handle);


The only error I came across was
Invalid query: Duplicate entry '127'

and this was down to database table I had created as I had the 'id' field set to TINYINT(3) - the resolution was to change this to INT(6)

Thursday, 12 June 2008

php strtotime returning 1970-01-29 - Adding month to date

Adding a month to a date
I was having problems using strtotime. The line i was using was

$next_available_date_end = strtotime("+2 months", next_available_date_start);

and the result I was getting was the date

I'm not sure why but opted to use mktime instead.
Here is how I accomplished this

$original_date = 2008-12-01;

$original_date_array = explode('-', $original_date ); // splits the date up

list($temp_year, $temp_month, $temp_day) = $original_date_array; // puts the array into the value year,month, day in sequence required

$temp_month++; // adds a month - we can do this because PHP will interperate 13 as the January in the next year

$date_a_month_on= date('Y-m-d', mktime(0, 0, 0, $temp_month, $temp_day, $temp_year));

for more on dates check

Monday, 2 June 2008

Passing variables around a class

I'm expecting a fair few of my following blogs to be about using Classes.
It's one of the tools of PHP that I have not really used. Functions yes but
not Classes, I have however hve been trying to use other peoples classes.
This I feel is bad pracise without fully understanding how and why classes
should be used.
I have been using the class activecalender which can be found at for a booking script. The changes I have been making to
class have been hacks to the code itself. After some studying into classses
it seems this is not the best practise but what i should do is make an
extended class, known as a child class.

'class myclass extends myparent'

Child classes then inherent member functions and member variables from its
parent. I will be coming back to this topic in a future blog, firstly I will
be looking at repackaging some of my own code into classes.
My original problem that has created this tipping point was that I could not
pass variables around the class . The solution is very simple.
in the Call up to the class set the value of the variable you wish to pass
around the class

$cal->item =$item;

from inside the class set up variable

var = $item;

and form inside the function


it's that easy!!!

Thursday, 29 May 2008

testing for File with file_exists

in my code I have a check to see if there is a thumbnail image if not I then resize the image and make a thumbnail. Before running I need to check that I have a big image to crop in the first place.
I do this with
if (!file_exists($thumbnailImg) && file_exists($imgFull))

however the argument file_exists($imgFull) comes back as TRUE even if the folder exists.
one way to get around this problem would be on the command

$imgFull = $pathFull.$img1;
I could check on $img and if it doesn't exist fill it with a value that deliberatly gives an error

if (strlen($img1) > 4){ // counts that $img1 has more than 4 characters ie 1.gif has 5

$imgFull = $pathFull.$img1;}
{$imgFull = $pathFull.'error.txt';}

you can check this code working at self catering cornwall .biz

Tuesday, 27 May 2008

Improving listings for

Hillside Glastonbury.

Earlier this month I did some general maintenance work for Hillside Glastonbury B&b and Self Catering . As well as adding lightview image viewer so to make the viewing of images clearer and easier ( to see the effect check Primrose Cottage and click on the main image) I also added several features in the hope we would get the site a better listing with Google.

The idea was to intergrate the site with Googles applications more - There is a list of Google Business tools at Google Services. On this occasion I have added Google Search of Hillside Glastonbury, Google Map of Hillside, Ashwell Lane, Glastonbury, Somerset, BA6 8BG, Hillside Glastonbury Blog and Google Anayltics for accurate stats on our listing with them.

Friday, 9 May 2008

Oscommerce Adding a dropdown menu selector to catergories.php

This is a small section of a contribution that I am writing to add to the website

The site is made with oscommerce. The problem I had was this


I'm trying to write a contribution that includes adding extra value to my product tables.

I can get the code to work with an input field - but would ideally like to change this to a dropdown list. The code that is in question is


surferRecWeight); ?>

so instead of using tep_draw_input_field - i would like to use tep_draw_pull_down_menu. I know that the second arguement for the function tep_draw_pull_down_menu needs to be my array for the drop list. I have tried a couple of different ways to make the array ie

$ability_array = array('Expert', 'Average', 'Novice');


$ability_array = array(0 => 'Expert', 1 => 'Average', 2 => 'Novice');


$ability_array[0] ='Expert';
$ability_array[1] = 'Average';
$ability_array[2] = 'Novice';

either way I get the same result which is that the drop down list only has the first letter of my array element - 'e','a',' & 'n'.

does anyone know why. I know that the function allows strings more than one character ?

the code I am using to call up the function is

echo tep_draw_separator('pixel_trans.gif', '24', '15') . ' ' . tep_draw_pull_down_menu('surferRecAbility', $ability_array, $pInfo->surferRecAbility);

///////////////////END OF FORUM ENTRY//////////////////////////////

A very odd problem indeed, To solve this i wrote a hack ( probably very ugly) - after following the trail of the problem here the function that I needed to change was in admin/includes/functions/html_output.php and the function in question was tep_draw_pull_down_menu. so instead of messing this function up, after all every other pull down menu in admin seems to work fine! I created a new one. which is as follows


function tep_draw_pull_down_menu_two($name, $values, $default = '', $parameters = '', $required = false) {
$field = '';

if ($required == true) $field .= TEXT_FIELD_REQUIRED;

return $field;


the only changes here are in $values[$i]. this is a much simplified version of what was there before, I take it because I created an array without keys etc that this is why it never worked. another solution therefore would be to rewrite the array in a format in keeping with oscommerce. However due to time constraints I will push on with the ugly hack ;)

Thursday, 1 May 2008

Making sure that theres no gaps in the filenames of image uploads.

The problem that needed to solved here was that users could upload there own images - and if the filename they were uploading has gaps or whitespace.
It took me a while to get my head around this one, eventhough the solution is fairly simple.
If you have solving the same problem here are a couple of links that may help. Firstly I posted this problem on a developer network forum. you can see that post at .
A tutorial that helps understand how file upload works in php is

Any back to my code.

What I needed to do first was check to check if theres any spaces and replace with '_'

$img1 = str_replace ( ' ', '_', $img1 );


then in move_uploaded_file change it to

$res = move_uploaded_file($_FILES['img1']['tmp_name'], $abpath .

staright forward, I have no idea now why I couldn't get my head around this straight away.

Tuesday, 29 April 2008

OSCOMMERCE Hide Categories & Products add on

I was trying to install the contribution for hiding product catergories on a heavily modded Oscommerce store -

this contribution can be found at,5907/category,all/search,Hide+Categories+%26+Products

Following the instructions I got everything to work ok except for in the admin area, where we now have a a green and red circle that light up when the folder is active or inactive. After installing the contribution then all buttons would come up red.

the contribution code displaying these items is as follows


if ($categories['categories_status'] == '1') {
echo tep_image(DIR_WS_IMAGES . 'icon_status_greenl.gif', IMAGE_ICON_STATUS_GREEN, 12, 12) . '  ' . tep_image(DIR_WS_IMAGES . 'icon_status_red_lightl.gif', IMAGE_ICON_STATUS_RED_LIGHT, 12, 12) . '';
} else {
echo '' . tep_image(DIR_WS_IMAGES . 'icon_status_green_lightl.gif', IMAGE_ICON_STATUS_GREEN_LIGHT, 12, 12) . '' . '  ' . tep_image(DIR_WS_IMAGES . 'icon_status_redl.gif', IMAGE_ICON_STATUS_RED, 12, 12); }

after running test i discovered that the part of the code running this test

$categories['categories_status'] == '1'

was not receiveing any value. So I wrote this hack (albeit ugly and not in the preffered oscommerce format it does work !!)

if ($categories['categories_status'] == '1') {


$categories_id = $categories['categories_id'] ;
$selectquery = "SELECT * FROM categories WHERE categories_id = $categories_id ";
$result = mysql_query($selectquery)
or die ("Query failed");
$row = mysql_fetch_array($result);

if ($row['categories_status'] == '1') {

making sure there's no blank listing on Random search

On the front page of my latest project at I have six boxes that advertise properties on the database randomly.

The main work horse of this code is in the mysql query that searches for a listing

$selectquery = "SELECT * FROM listings ORDER BY RAND() LIMIT 1";

li.img1 > 0 AND

what i would like to do is make sure I am not displaying a blank listing - the following statement will check that two values and if they are ok then that row will be included in the random search.

$selectquery = "SELECT * FROM listings li WHERE li.img1 > 0 AND > 0 ORDER BY RAND() LIMIT 1";

we can also add further filters - for example it may be cool just to list randomly some of the cheapest properties - this next search will only list properties that are under a value of £300

$selectquery = "SELECT * FROM listings li WHERE li.img1 > 0 AND > 0 AND <= 300 ORDER BY RAND() LIMIT 1";

Thursday, 24 April 2008

Creating Pagination for my search results

Pagination is where in receiving search results you have too many to list on one page. So therefore you would like to have some sort of links system where you can click on '<>' and get the next 10 or however many you wish.

to solve this in my search results I had tried downloading other peoples classes but after some head scratching and figuring out could not adapt them to the search script I had already wrote. In the end I decided it'd be better if I wrote the code myself. Here is how I reached my final aim - I am hoping to write this in such a way that it may help others try to get there heads around how this will need to work for them.

In my script I will have the value $limit - this is the amount of results per page that we want per page.

the selectquery runs the search - Yours will be specfic to yourselves

from that selectquery we need to find out how many results there are.


Next I want to find out if there is indeed more results that will fit onto 1 page and if so how many pages are there in total

if ($numrows > $limit){ // this calculates whether theres enough results to have pagination
$pagesExact = $numrows / $limit; // how many pages?

$pages = ceil($pagesExact); // gives the next highest round figure

In the future at this stage in the script it may be the case that we are already on another page of search results. What I mean is that at the top of my search script I will check to see what page of the search this. I am going to send this to further pages in the URL using $_GET

>> $currpage = $_GET['currPage'];

Next I'll check to see if there is already a $currPage value - if not I'll take it as red were on page 1.

if (!$currPage) {
$currPage = 1;


At this point in code I want to get the results that I am going to display. So that I only display the set that the page requires I am going to use the mysql command of LIMIT and OFFSET.
adding LIMIT to mysql will only give you that number of rows. By using OFFSET then we can offset the search ie by using an offset value of 10 then thats the row it will start at. Consider..


if ($currPage > 1){
$offset = ($currPage-1) * $limit;

$selectquery .= " LIMIT $limit OFFSET $offset ";
}else {
$selectquery .= " LIMIT $limit ";

what I've done here is that if the search is more than 1 then I run the query with an offset. I calculated that the currpage ( example =2) take away 1 (example =1) times the limit (example 10) will equal (example 10) the offset that we need.

Now here comes the code to show the previous page if we need it

if ($currPage>1) {
$nPage=$currPage - 1;

print "\<a href="$PHP_SELF?currpage="$nPage\" wordsearch="TRUE&find="><<Prev 10&nbsp ";


firstly we make it display if there is more than 1 page here to display. $currPage>1

Next we give the link the right number so when redirecting back to this script we know what page we're on. $nPage=$currPage - 1

The code for next>> page is similar


if ($currPage < $pages) { $nPage=$currPage + 1;

print " \<a href="$PHP_SELF?currpage="$nPage\" wordsearch="TRUE&find=">Next 10 >>";


but we add a page to $nPage.

Next we give details of how many searches are being shown and how many results there are.


if ($currPage==1){

if ($offset > $numrows){

$offset = $numrows;

echo "

Showing results $currPage to $offset of $numrows

else {

$countresults = ($currPage - 1) * $limit; // we need to take away 1 from current page as page 3 needs to return results 20-30

$countAdd10 = $countresults + 10;
if ($countAdd10 > $numrows){

$countAdd10 = $numrows;}echo "

Showing results $countresults to $countAdd10 of $numrows



And thats it. Any suggested improvements let me know.

Tuesday, 22 April 2008

Resizing Images - Server Side

Resizing Images

On our soon to be new website we have an area for landlords to go into and enter their images. This then uploads to our server into an individual folder. On the index page of our website we have a random product viewer. Here we are showing randomly a range of properties. What I need to is check to see if there if a thumbnail of the image. If not create one. You will need to have GD2 uploaded on your server to run this. You can check that by running the function phpinfo().

Heres the code


img1=$row["img1"]; // heres our image
$rid=$row['rid']; // this is a unique number for every property and I have used this to name each folder of images for each properties// here comes the image search - $pathFull = $abpath.$rid.'/'; // this gives us our root to image folder - $abpath is set in config.php$imgFull = $pathFull.$img1; // with image as well $thumbnailImg = $pathFull.'160thum'.$img1; // where are thumbnail will be if not already

if (!file_exists($thumbnailImg)) { // if we haven't got an thumbnail then make oneif (file_exists($imgFull)) { // if the image doesnt exist the following code would have produced an error

$origImage = $imgFull; // just renaming for more clarity

$imageSizes = GetImageSize($origImage); // get the sizes of the big image - we are going to make sure the image is kept in proportion

$imageheight = $imageSizes[1]; // get the sizes of the big image height

$thumbWidth = 160; // how big do you want the thumbnails - you can change this to any height

// here comes the calculation to work out thumbheight

if ($thumbHeight){ // making sure we have a value to work with so to not cause an error

if ($imagewidth > $thumbWidth){ // making sure the value can divide, again so to not cause an error

$divisionBy = $imagewidth / $thumbWidth;
$thumbHeight = $imageheight / $divisionBy;


else {

$thumbHeight = $imageheight; // if the image is smaller than 160 then leave it alone


resizeImage($origImage, $thumbnailImg,$thumbWidth, $thumbHeight); // runs the function see below
if (!file_exists($imgFull)){ // if there's no image we can display a message of 'no pic available'

$displayimg = 'nopic.gif';}
$displayimg = $row['rid'].'/160thum'.$row["img1"];


then all we have do is wrap $displayimg in an img src tag -
ONE MORE THING -- you'll need this function to get this all to work. I've put mine in a folder /includes/functions/images.php but you can put it on the same page if you want.

function resizeImage

($src_file, $dst_file, $max_width, $max_height)
{ // Formats we will handle.
$formats = array('1' => 'gif', '2' => 'jpeg', '3' => 'png');

// Get info on the image.

if (!$sizes = getimagesize($src_file))
return false;
// A known and supported format?

if (!isset($formats[$sizes[2]]) !function_exists('imagecreatefrom' .$formats[$sizes[2]]))
return false;
// Create image from file.
$imagecreatefrom = 'imagecreatefrom' . $formats[$sizes[2]]; if (!$src_img = $imagecreatefrom($src_file))
return false;
// Calculate the new size.
$max = array('width' => $max_width, 'height' => $max_height);
$dst['width'] = $src['width'] = $sizes[0];
$dst['height'] = $src['height'] = $sizes[1];
foreach (array('width' => 'height', 'height' => 'width') as $k => $v)
if (!empty($max[$k]) && $dst[$k] > $max[$k]) {
$dst[$k] = $max[$k];
$dst[$v] = floor($src[$v] * $max[$k] / $src[$k]);

// Create true color image.
$dst_img = imagecreatetruecolor($dst['width'], $dst['height']);

// Do the resize.
if(!imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dst['width'],$dst['height'], $src['width'], $src['height']))
return false;

// Save image to file.
imagejpeg($dst_img, $dst_file);

// Free the memory.

return true;}

Monday, 21 April 2008


The Problem: when going into the editlisting page the drop down lists default to there original settings. Therefore if the user doesn't fully check this everytime they will change their details
The solution:
in the HTML of the form the

$bed = $row["bed"];if ($bed == 1){
echo 'SELECTED';

Sunday, 20 April 2008

Make image upload unique to all visitors

The Problem: we will be having a number of users - at present all their photos will be going into one folder. So if they have the same filenames the latest picture will over write the rest and show on everyone elses listings.

The Solution.

when landlords upload their images if we then upload these images into a folder that is unique ( taken from a unique number on their database )

--Next stage >>

So basically we'll need to add to the admin section in landlords where they add and edit images. In my project this is landlords/edit.php & landlords/add.php

And then we'll need change all pages that display properties to read from the correct folder.
In my project this is - index.php & members/details.php & search/index.php



I have a value in this page named $abpath -
this value is set in includes/config.php and is for the images folder. So what I need to do is change $abpath to includes the unique folder number. Create the folder. Chmod the folder ( set the write settings). And then send the image to that folder.

So back to that unique folder. In my mysql table 'listings' I have a colomn '$rid' which is unique to all properties. Firstly I need to get that number, it gets created in landlords/add.php on the insert on line 131

INSERT INTO listings (llid, rtype, addone, addtwo, city, state, postcode1, postcode2, pets,websiteURL , descrip, bed, bath, garage, yard, utilities, rent, deposit, listdate, starRating, img1, img2, img3, img4, img5, img6, img7, img8) VALUES ('$llid', '$proptype', '$add', '$addtwo', '$city', '$state', '$postcode1', '$postcode2', '$pets','$websiteURL' , '$description', '$bedroom', '$bathroom', '$garage', '$yard', '$utilities', '$rent', '$deposit', '$tdate', '$starRating', '$imgone', '$imgtwo', '$imgthree', '$imgfour', '$imgfive', '$imgsix', '$imgseven', '$imgeight'

Underneath I have used

$listings = mysql_query("SELECT * FROM listings WHERE llid='$llid' AND img1='$imgone' AND postcode2='$postcode2' ");
$listingRow = mysql_fetch_array($listings);

$rid = $listingRow['rid'];

this is a tight as I think I need to make the search on this detail. However if we think landlords will be using more than one property with the same main image and postcode then we may have a problem.
Otherwise we should be getting our unique number stored in $rid back to use to make a folder.


$abpath = $abpath .$rid.'/';

// this sets the new path where we want our folder


if ( !is_dir($abpath)){
mkdir($abpath, 0700);

// if this directory doesn't exist creat it and set the security level




this page is much easier as $rid is already in use so all we need to add is on line 162 ENTER

$abpath = $abpath .$rid.'/';



search for all images -

code for images will appear as such


this needs to be changed to



Tuesday, 15 April 2008

using CASE instead of If and ELSEIF

Using Switch instead of If and Elseif

I have a script that is being giving the month as a value and I would like to return the value of the month in text - ie January.

So here's the code in the most obvious hack

$month= date('m');

if ($month == 1 ) {
$month= 'January';
elseif ($month == 2 ) {
$month= 'February';
elseif ($month == 3 ) {
$month= 'March';
elseif ($month == 4 ) {
$month= 'April';
elseif ($month == 5 ) {
$month= 'May';
elseif ($month == 6 ) {
$month= 'June';
elseif ($month == 7 ) {
$month= 'July';
elseif ($month == 8 ) {
$month= 'August';
elseif ($month == 9 ) {
$month= 'September';
elseif ($month == 10 ) {
$month= 'October';
elseif ($month == 11 ) {
$month= 'November';
elseif ($month == 12 ) {
$month= 'December';


it's in my understanding that using switch should tidy this code up somewhat.

my statement should then look like this.

switch ($month) {

case 1:
$month= 'January';
case 2:
$month= 'February';
case 3:
$month= 'March';
case 4:
$month= 'April';
case 5:
$month= 'May';
case 6:
$month= 'June';
case 7:
$month= 'July';
case 8:
$month= 'August';
case 9:
$month= 'September';
case 10:
$month= 'October';
case 11:
$month= 'November';
case 12:
$month= 'December';


Tuesday, 1 April 2008

Follow up post to Yesterdays calendar script notes

if you followed the code from yesterday you'll notice a couple of things.

1. this isn't a tutorial - Sorry. more like the ramblings of a

troubled programmer. These notes are as much for my own learning

progress, and I am not really taking the time to double read these notes.

2. there were loads of gaps in the code.

I hope these notes are clear enough though to help trigger

somepeoples understanding of php/mysql.


Mainly I should have explained the mysql setup and what's being

achieved. here's the statement for the mysql I have used in this

part of the booking calender project

CREATE TABLE `landlords` (
`lid` int(6) unsigned NOT NULL auto_increment,
`fname` varchar(55) default '0',
`lname` varchar(55) NOT NULL default '',
`propertyCount` int(5) NOT NULL,
`phone` varchar(25) default '0',


CREATE TABLE `listings` (
`rid` int(15) NOT NULL auto_increment,
`llid` int(6) NOT NULL default '0',
`rtype` varchar(25) NOT NULL default '',
`addone` varchar(75) NOT NULL default '',
`addtwo` varchar(75) NOT NULL default '',
`city` varchar(35) NOT NULL default '',
`state` varchar(25) NOT NULL default '',
`postcode1` varchar(6) NOT NULL,
`postcode2` varchar(6) NOT NULL,
`pets` char(3) NOT NULL default '',
`websiteURL` varchar(120) NOT NULL,
`descrip` text NOT NULL,
`bed` int(2) NOT NULL default '0',
`bath` char(2) NOT NULL default '',
`garage` char(3) NOT NULL default '',
`yard` char(3) NOT NULL default '',
`utilities` varchar(5) NOT NULL default '',
`rent` varchar(10) NOT NULL default '0.00',
`deposit` varchar(10) NOT NULL default '0.00',
`listdate` date NOT NULL default '0000-00-00',
`img1` varchar(25) NOT NULL default '',
`img2` varchar(25) NOT NULL default '',
`img3` varchar(25) NOT NULL,
`img4` varchar(25) NOT NULL,
`img5` varchar(25) NOT NULL,
`img6` varchar(25) NOT NULL,
`img7` varchar(25) NOT NULL,
`img8` varchar(25) NOT NULL,
KEY `lstid` (`rid`),
KEY `city` (`city`),
KEY `pets` (`pets`),
KEY `bed` (`bed`),
KEY `bath` (`bath`),
KEY `garage` (`garage`),
KEY `yard` (`yard`)


CREATE TABLE `users` (
`userid` int(10) NOT NULL auto_increment,
`llid` int(10) NOT NULL default '0',
`fname` varchar(35) NOT NULL default '',
`lname` varchar(35) NOT NULL default '',
`email` varchar(75) NOT NULL default '',
`addone` varchar(75) NOT NULL default '',
`addtwo` varchar(75) NOT NULL default '',
`city` varchar(35) NOT NULL default '',
`state` varchar(25) NOT NULL default '',
`zip` varchar(15) NOT NULL default '',
`phone` varchar(25) NOT NULL default '',
`passwd` varchar(35) NOT NULL default '',
`tdate` date NOT NULL default '0000-00-00',
KEY `userid` (`userid`),
KEY `email` (`email`),
KEY `passwd` (`passwd`),
KEY `date` (`tdate`)


CREATE TABLE `weeks` (
`llid` int(5) NOT NULL,
`rid` int(5) NOT NULL,
`dayID` int(2) NOT NULL,
`monthID` int(2) NOT NULL,
`yearID` int(4) NOT NULL

-- Dumping data for table `weeks`

INSERT INTO `weeks` (`llid`, `rid`, `dayID`, `monthID`, `yearID`)

VALUES (21, 38, 15, 12, 2008),
(21, 38, 1, 1, 2008),
(21, 38, 15, 12, 2008);


You may have also noticed that there is a major problem with the

code from yesterday. Being that it was only doing a check on

'landlord' and not on each individual listing. Fine if landlords

only list 1 product or are available on the same day.

the main thing I had to change is the mysql statements in


Here are the changes that I made.



if ($_GET['dayID'] && $_GET['monthID'] && $_GET['yearID'] ){




// db insert and redirection
mysql_query ("INSERT INTO we


mysql_query ("INSERT INTO weeks (llid, rid, dayID, monthID,

yearID) VALUES ('$llid', '$rid', '$dayID', '$monthID', '$yearID')");


mysql_query ("DELETE FROM weeks WHERE


mysql_query ("DELETE FROM weeks WHERE (llid = '$llid' && rid

='$rid' && dayID ='$dayID' && monthID ='$monthID' && yearID

='$yearID') ");


$dateRst =mysql_query("SELECT * FROM weeks WHERE


$dateRst =mysql_query("SELECT * FROM weeks WHERE (llid='$llid' &&

rid='$rid') ");



open Landlords index.php


echo $row["city"];


echo "
href=\"calendarListingEdit.php?id=".$row["rid"]."\">Set Available


Saturday, 29 March 2008

Active Calender to MySQL script

i am looking at making a booking form for a website.
What I need to do is find a calender - make it clickable and get it to send information to my mysql database.

pages to adapt to get the result I need

open /source/activecalendar.php


function mkDay($var)

REPLACE the function with

function mkDay($var){

// delete string // key to this is function mkDelUrl that appears below


// I have added the following code to give the full date and a week count with year number :Deej
$this->thedaysfulldate = $this->actday.$this->actmonth.$this->actyear;

$weekCount = $this->getWeekNum($var).$this->actyear;

if ($this->javaScriptDay) $linkstr="javaScriptDay."(".$this->actyear.",".$this->actmonth.",".$var.")\">".$var."";
if ($this->isEvent($var)){
if ($this->eventUrl){
elseif (!$this->dayLinks) $out="eventID."\">".$var.$eventContent."";
// the following is a highlighted box
// to delete from mysql this will be the place to add a get link for removal
else $out="eventID."\">".$deleteStr.$eventContent."";
elseif ($var==$this->selectedday && $this->actmonth==$this->selectedmonth && $this->actyear==$this->selectedyear){
if (!$this->dayLinks) $out="cssSelecDay."\">".$var.$eventContent."";
else $out="cssSelecDay."\">".$linkstr.$eventContent."";
elseif ($var==$this->daytoday && $this->actmonth==$this->monthtoday && $this->actyear==$this->yeartoday){
if (!$this->dayLinks) $out="cssToday."\">".$var.$eventContent."";
// underneath is the white highlighted box
else $out="cssToday."\">".$linkstr.$eventContent."";
elseif ($this->getWeekday($var)==0 && $this->crSunClass){
if (!$this->dayLinks) $out="cssSunday."\">".$var.$eventContent."";
// the following is on the sunday link that works
else $out="cssSunday."\">".$linkstr.$eventContent."";
elseif ($this->getWeekday($var)==6 && $this->crSatClass){
if (!$this->dayLinks) $out="cssSaturday."\">".$var.$eventContent."
// the following is on the saturday link that works
else $out="cssSaturday."\">".$linkstr.$eventContent."";
if (!$this->dayLinks) $out="cssMonthDay."\">".$var.$eventContent."
// the following is on the day link that works
else $out="cssMonthDay."\">".$linkstr.$eventContent."";

return $out;



function mkUrl


PRIVATE mkDelUrl() -> creates the day and navigation link structure
function mkDelUrl($year,$month=false,$day=false){
if (strpos($this->url,"?") === false) $glue="?";
else $glue="&del";
if (strpos($this->urlNav,"?") === false) $glueNav="?";
else $glueNav="&";
if ($year && $month && $day) return $dayLink;
if ($year && !$month && !$day) return $yearNavLink;
if ($year && $month && !$day) return $monthNavLink;


-> i'm just going to list the important bits of the page here. so you'll need to format it how you want.

in the php tags

$myurl=$_SERVER['PHP_SELF']."?css=".@$_GET['css']; // the links url is this page
$yearID=$_GET['yearID'];; // init false to display current year
$monthID=false; // init false to display current month
$dayID=false; // init false to display current day
$cal=new activeCalendar($yearID,$monthID,$dayID);
$cal->enableDayLinks($myurl); // enables day links
$thisYear=$cal->actyear; // get the current year
$arrowBack="<<"; // arrow back
$arrowForw=">>"; // arrow forward

$_SESSION['uid'] = $uid;
$_SESSION['pwd'] = $pwd;

$rst=mysql_query("SELECT * FROM users WHERE email='$uid' and passwd='$pwd'");
$row = mysql_fetch_array($rst);


$dateRst =mysql_query("SELECT * FROM weeks WHERE llid='$llid'");

while ($rows = mysql_fetch_array($dateRst))
$dayID = $rows['dayID'];
$monthID = $rows['monthID'];
$yearID = $rows['yearID'];
$llid = $rows['llid'];

$weekFinish = $dayID+7;

for ($x=$dayID;$x<=$weekFinish;$x++) $cal->setEvent($yearID,$monthID,$x); // create a class="event" from 10th till 20th on March each year


//$cal->setEvent("08","1","17","event"); // create a class="event" on the 17th Jan each year

//for ($x=5;$x<=12;$x++) $cal->setEvent("08",$x,"24"); // create a class="event" on the 23th from May till December each year
$cal->enableYearNav($myurl,$arrowBack,$arrowForw); // enables navigation controls
$cal->enableDatePicker(2008,2018,$myurl); // enables date picker (year range 2000-2010)

if ($_GET['dayID'] && $_GET['monthID'] && $_GET['yearID'] ){

$dayID = $_GET['dayID'];
$monthID = $_GET['monthID'];
$yearID = $_GET['yearID'];

// the mysql query will depend on what information your using in your project

$rst=mysql_query("SELECT * FROM users WHERE email='$email' and passwd='$passwd'");
if ($row = mysql_fetch_array($rst))

// db insert and redirection
mysql_query ("INSERT INTO weeks (llid, dayID, monthID, yearID) VALUES ('$llid', '$dayID', '$monthID', '$yearID')");

echo 'These details have been added to the database '.$dayID.' '.$monthID.' '.$yearID.' ';


if ($_GET['deldayID'] && $_GET['delmonthID'] && $_GET['delyearID'] ){

$dayID = $_GET['deldayID'];
$monthID = $_GET['delmonthID'];
$yearID = $_GET['delyearID'];

// the mysql query will depend on what information your using in your project

$rst=mysql_query("SELECT * FROM users WHERE email='$email' and passwd='$passwd'");
if ($row = mysql_fetch_array($rst))

// db insert and redirection

// this is where I'm upto - i know its the following statement at fault
// as when I change & to AND it deletes all my records under llid
mysql_query ("DELETE FROM weeks WHERE (llid = '$llid' && dayID ='$dayID' && monthID ='$monthID' && yearID ='$yearID') ");

echo 'These details have been deleted from the database '.$dayID.' '.$monthID.' '.$yearID.' ';



call up the class with

showYear(); ?>


Thats it. I am aware that this is somewhat of a hack and am always looking a improving my code. I think that ideally a class addition somehow would have been better, rather than changing function mkDay.
Anyone reading this who can help me out on that please let me know.


Friday, 28 March 2008

using .$_SERVER['']. - to get the url in the link

Firstly I know it's been a while since I've used my blog, but I do now intend to keep it much more uptodate.

I will try and write notes on anything I've had to search for on the web, looked in forums etc. Sometimes these write ups may need to be uploaded at the end of project once it goes live.

Know to the latest problem -

which server command should i use just to put the URL in the link - with no folders etc.

This is useful when the page thats sending the link is in another folder -

Example - you may be in /admin and the script displaying link is in /includes/ and then you want to access the same script from your root folder.

$_SERVER['HTTP_HOST'] - is the one you need - this give the result

however when link you will need to put http:// inside the a href, otherwise your links may look like this -