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 http://www.oscommerce.com/community/contributions,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

[code]

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); }
?>
[/code]


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 !!)

FIND:
// CATEGORY STATUS
if ($categories['categories_status'] == '1') {

REPLACE WITH

$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);


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

making sure there's no blank listing on Random search

On the front page of my latest project at www.selfcateringcornwall.biz 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

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

[/code]
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.

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

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

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

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.
[code]
$numresults=mysql_query($selectquery);
$numrows=mysql_num_rows($numresults);

[/code]

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

[code]
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
}
[/code]

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.

[code]
if (!$currPage) {
$currPage = 1;

}
[/code]

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..

[code]

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

$selectquery .= " LIMIT $limit OFFSET $offset ";
}else {
$selectquery .= " LIMIT $limit ";
}
[/code]

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
[code]

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

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

[/code]

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

[code]

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

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

[/code]

but we add a page to $nPage.

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

[code]

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

";
}

}
[/code]

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';}
else
{
$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.
imagedestroy($src_img);
imagedestroy($dst_img);

return true;}



Monday 21 April 2008

making

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


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

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



######################################################################

landlords/add.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.

THEN UNDERNEATH ENTER

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

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



THEN UNDERNEATH ENTER

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


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


THATS ALL FOR THIS PAGE.




######################################################################



landlords/edit.php

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.'/';


##############################################################


ON ALL DISPLAY PAGES


search for all images -

code for images will appear as such

"../images/"row['img3']."\"


this needs to be changed to

"../images/".$row['rid']."/".$row['img3']."\"




AND THATS IT --

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.

http://uk.php.net/manual/en/control-structures.switch.php

my statement should then look like this.


switch ($month) {

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

}

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',
PRIMARY KEY (`lid`)
) ENGINE=MyISAM AUTO_INCREMENT=25 DEFAULT CHARSET=latin1

AUTO_INCREMENT=25 ;


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`)
) ENGINE=MyISAM AUTO_INCREMENT=40 DEFAULT CHARSET=latin1

AUTO_INCREMENT=40 ;



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`)
) ENGINE=MyISAM AUTO_INCREMENT=21 DEFAULT CHARSET=latin1

AUTO_INCREMENT=21 ;


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
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- 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

landlords/calendarListingEdit.php

Here are the changes that I made.

>>>>>>>>>>>>>>>>>>>>>>

FIND:

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


ABOVE ADD:

$rid=$_GET["id"];


FIND:

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


CHANGE THIS LINE TO.

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

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


FIND:

mysql_query ("DELETE FROM weeks WHERE


CHANGE THIS LINE TO.

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

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

='$yearID') ");


FIND

$dateRst =mysql_query("SELECT * FROM weeks WHERE

CHANGE THIS LINE TO.


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

rid='$rid') ");


SAVE

#############################

open Landlords index.php


FIND:

echo $row["city"];

UNDERNEATH

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

Dates
";