0

Hello guys ;)
Im quite new to PHP and i run into a problem. I was given a PHP task to do and its got to be submited by 27th this month in my uni... unfortunately i was not attending any Web programming class as i was so into Java that i have forgot about whole world :( and now im kinda stuck.

The coursework is:

Use a text editor to make a comma delimited text file containing data of properties for sale with the following fields/columns: Postcode, Price(thousands), imagefilename, Visits
(Eg: HA13TP, 250,house1.jpg, 3)

1. Display all property information. The screen display can be any simple and sensible layout. Call the script plist.php.
Important: Read in the file and then access one file line at a time and display each field separately (don=t display the whole line in one go). Within your code you must write a subroutine which takes in a string of delimited text (eg. one line of the comma delimited file input) and gives back then nth item of text found between the commas. In this way you can ask the subroutine to extract the first item 1 (Postcode) and when the result is returned you can display it, then the subroutine should extract the second item 2 (Price) and then display the result, etc. Then loop to get the next text line.

2. Display all property details below a maximum price (the user enters the price in a field on a static web form - the price is read in by the script and used to find the property details as the script reads through the property text file) Call the script maximum.php

3. Allow the user to enter a search term - and the web page will display the full details of all the properties containing the user=s search term included in part of any field value. Call the script psearch.php

4. Display on the screen all details of properties which are below a maximum price entered by the user, and allow a user the option of selecting any of the properties shown (read the property file and for each property shown display the property details in a form with a checkbox next to the property details ). ( available.php )

5. The user intends to visit properties they have selected in part 4. When the form for part 4 is submitted a script should work out which properties have been selected by the user and then add one to the Visits field of the selected property. You must fully understand any code you use.
( visit.php )

I would be very grateful if someone would help me out on this one, perhaps how to even start this thing, and also some nice useful links with some info i could learn from would be great. In fact any help would be appreciated :) !

Cheers guys

2
Contributors
23
Replies
31
Views
5 Years
Discussion Span
Last Post by infinitus
Featured Replies
  • I would suggest you try breaking the problem down into smaller tasks, for which you then write the code to solve each. So, for your maximum price task you need to: 1. Enter a maximum price and submit the web form. 2. Store the submitted maximum price value in a … Read More

  • The problem is the '.' in the prices. Remove them and it should work. [CODE]// Lets find the comparison price, if specified. Otherwise assume 250.000 $comparison_price = isset($_POST['price']) ? $_POST['price'] : '250.000'; $filename = "properties.txt"; $filepointer = fopen($filename,"r"); // open to read file $myarray = file ($filename); for ($mycount = … Read More

0

Also forgot to mention, what would be suitable program to code in PHP ??, can i use my dreamweaver ??

0

Plist file code

<?php
$file = fopen("properties.txt", "r") or exit("Unable to open file!");
while(!feof($file))
  {
  echo fgets($file). "<br />";
  }
fclose($file);
?>

Maximum file code

<?php
$file = fopen("properties.txt", "r") or exit("Unable to open file!");
$contents = file_get_contents($file);
fclose($file);


?>

This is what i came up with so far :( and im noot good at this ;/

0

guys can any one help me on this ?? i am not a php pro i do research on internet but if someone could help me out would be great thank you !

0

To give you a large hint, look at the function fgetcsv. This page will also include a code example demonstrating how to use the function.

The function reads in a CSV file one line at a time, and stores the data in a numerically indexed array, thus allowing you to access the nth item in a line as required.

0

Oki thank you will look at it and work from there, will post more code and whatever i have done :) later on thank you

0
<?
 $filename = "properties.txt";
 $filepointer = fopen($filename,"r");  // open to read file
 $myarray = file ($filename);
 for ($mycount = 0; $mycount < count($myarray); $mycount++ )
    {			// one input line at a time
      $aline = $myarray[$mycount];  
      words($aline);	
    }
fclose ($filepointer);
function words($aline)
	{
		for($mycount=0; $mycount<str_word_count($aline); $mycount++)
			{
				$field = &getvalue($aline, $mycount);				
				print $field . "<br/>";
			}
	}
function getvalue ($text, $commaToLookFor)
	{   
		$intoarray = explode(",",$text);
		return  $intoarray[$commaToLookFor];  
	}
?>

Ok so this is the code i got, and i think it solves the question 1. Now i need to do if statement for questions 2.

Also can any one simplify the code i provided ?? or is that simple enough ?i mean if there is another way of presenting same thing but in much more efficient way i would like to see :)

0

Well done for making an effort. Yes, the code can be simplified and in fact the function I pointed you at before offers an example, which does almost exactly what you have created there:

// Taken from: http://php.net/manual/en/function.fgetcsv.php#example-2157
// I have modified the example to suit your requirements more closely

if (($handle = fopen('test.csv', 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 0, ',')) !== FALSE) {
        echo implode('<br />', $data) . '<br />;
    }
    fclose($handle);
}

If this is for coursework however, I would most likely use your own version of the code to avoid possible plagiarism issues. If I were your lecturer, I would know to check PHP.net for examples. They might however appreciate that you recognised the code did as you required and that you knew how to reuse it properly, given that it's origins are cited appropriately.


Part 2 will require a form. They are pretty easy to use, and there are loads of examples around. Tizag.com has some very simple tutorials.

You would then need to know which field (array index) on a line contains the property price, and compare whether it is less than the price specified. Easy enough?

0

http://www.infinit0s.cba.pl/coursework1/index.html link to simple form with prices
code

<html>
<body>
<h4>Estage Agency coursework 1</h4>
<form action ="maximum.php" method ="post">
<select name ="price">
	<option>Less then 100.000</option>
	<option>Less then 150.000</option>
	<option>Less then 200.000</option>
	<option>Less then 250.000</option>
	<option>Less then 300.000</option>
	<option>Less then 500.000</option>
	<option>Less then 750.000</option>
</select>
<input type ="submit" />
</form>
</body>
0

double post by accident

quote" You would then need to know which field (array index) on a line contains the property price, and compare whether it is less than the price specified. Easy enough? "

How do i know that ? I mean i know that in my property.txt file price somes after 1st comma. so its like
NW13HA, 250.000, house1.jpg, 14. But how do i extract this price ?? from this array ?

Edited by infinitus: n/a

0

This is my maximum.php file

<?
 $filename = "properties.txt";
 $filepointer = fopen($filename,"r");  // open to read file
 $myarray = file ($filename);
 for ($mycount = 0; $mycount < count($myarray); $mycount++ )
    {			// one input line at a time
      $aline = $myarray[$mycount];  
      words($aline);	
    }
fclose ($filepointer);
$price = getvalue(1);
function words($aline)
	{
		for($mycount=0; $mycount<str_word_count($aline); $mycount++)
			{
				$field = &getvalue($aline, $mycount);
				//how to connect my index.html (form) so when i chose an option in form
				//it corresponds to an specified if statement??
                                //what to put inside ifs ??
				if($price < 100.000)
				{
				}
				elseif($price <150.000)
				{
				}
				elseif($price <200.000)
				{
				}
				elseif($price <250.000)
				{
				}
				elseif($price <300.000)
				{
				}
				elseif($price <500.000)
				{
				}
				elseif($price <750.000)
				{
				}
				else
				{
				}
				print $field . "<br/>";
			}
	}

function getvalue ($text, $commaToLookFor)
	{   
		$intoarray = explode(",",$text);
		return  $intoarray[$commaToLookFor];  
	}	
?>
0

To begin with, your form code isn't quite right. You missed the value attribute from your select options:

<html>
<body>
<h4>Estage Agency coursework 1</h4>
<form action ="maximum.php" method ="post">
<select name ="price">
	<option value="100.000">Less then 100.000</option>
	<option value="150.000">Less then 150.000</option>
	<option value="200.000">Less then 200.000</option>
	<option value="250.000">Less then 250.000</option>
	<option value="300.000">Less then 300.000</option>
	<option value="500.000">Less then 500.000</option>
	<option value="750.000">Less then 750.000</option>
</select>
<input type ="submit" />
</form>
</body>

When this form is submitted, it will do so to your maximum.php script. You can then access the price attribute via the $_POST array.

$price = $_POST['price'];

// However, it's always good practice to test for the existing of a value before attempting to access it.
// The following expression w = x ? y : z; is called a ternary operator. It's basically a condensed if/else statement 
$price = isset($_POST['price']) ? $_POST['price'] : '100.000';

You can then use the $price attribute value as your basis for comparison.

With regard to knowing where the property price will appear within the text file, I would expect this can be something you choose. You would need to know format of the file to be able to effectively parse it. Therefore, if the price appears after the first comma, it's index is 1, as arrays use 0 based indexing.

0
$price = isset($_POST['price']) ? $_POST['price'] : '100.000';

so this line is basicly

if($price < 100.000)
{
}

??

Also a properties.txt file is just plain notepad text comma delimited values... price comes after first comma
so

$price = getvalue(1);

getvalue is a function defined by me as

function getvalue ($text, $commaToLookFor)
{
$intoarray = explode(",",$text);
return $intoarray[$commaToLookFor];
}

So isn't that functions what is needed? i mean it separates values where the "," is and after the first coma value of (price whatever it is) comes... so i thought this value would be storred in $price

0
function words($aline)
	{
	$price = $_POST['price'];
	$price = getvalue(1);
		for($mycount=0; $mycount<str_word_count($aline); $mycount++)
			{
				$field = &getvalue($aline, $mycount);	
			
			if($price = isset($_POST['price']) <= $_POST['price'] : '100.000' )
				{									
					print $aline. "</br>";	
				}
			if($price = isset($_POST['price']) <= $_POST['price'] : '150.000' )
				{
					print $aline. "</br>";
				}
			if($price = isset($_POST['price']) <= $_POST['price'] : '200.000' )
				{
					print $aline. "</br>";
				}
			if($price = isset($_POST['price']) <= $_POST['price'] : '250.000' )
				{
					print $aline. "</br>";
				}
			if($price = isset($_POST['price']) <= $_POST['price'] : '300.000' )
				{
					print $aline. "</br>";
				}
			if($price = isset($_POST['price']) <= $_POST['price'] : '500.000' )
				{
					print $aline. "</br>";
				}
			if($price = isset($_POST['price']) <= $_POST['price'] : '750.000' )
				{
					print $aline. "</br>";
				}
			}
	}

when i run it i get this error
"Parse error: syntax error, unexpected ':' in /var/www/virtual/infinit0s.cba.pl/coursework1/maximum.php on line 20"
it doesnt recognize ":" character ??
sorry im lost :(

Edited by infinitus: n/a

0
<?
 $filename = "properties.txt";
 $filepointer = fopen($filename,"r");  // open to read file
 $myarray = file ($filename);
 for ($mycount = 0; $mycount < count($myarray); $mycount++ )
    {			// one input line at a time
      $aline = $myarray[$mycount];  
      words($aline);	
    }
fclose ($filepointer);

function words($aline)
	{

		for($mycount=0; $mycount<str_word_count($aline); $mycount++)
			{
				$field = &getvalue($aline, $mycount);				
			}
	}
$price = getvalue($text,1);
function getvalue ($text, $commaToLookFor)
	{   
		$intoarray = explode(",",$text);
		return  $intoarray[$commaToLookFor];  
	}	
							
			if($price = isset($_POST['price']) <= $_POST['price'])
				{									
					print $aline. "</br>";						
				}
			if($price = isset($_POST['price']) <= $_POST['price'])
				{
					print $aline. "</br>";
				}
			if($price = isset($_POST['price']) <= $_POST['price'])
				{
					print $aline. "</br>";
				}
			if($price = isset($_POST['price']) <= $_POST['price'])
				{
					print $aline. "</br>";
				}
			if($price = isset($_POST['price']) <= $_POST['price'])
				{
					print $aline. "</br>";
				}
			if($price = isset($_POST['price']) <= $_POST['price'])
				{
					print $aline. "</br>";
				}
			if($price = isset($_POST['price']) <= $_POST['price'])
				{
					print $aline. "</br>";
				}
				
?>

So i took out this bit and putted it outside the loop. But it prints only last entry or last thing in array. I know that this is probably the last value stored in $aline is the last value from the loop. But when i tried to wrap this piece of code (isset ...) into loop i was getting bunch of erros...

Also i was thinking why this didnt work either

if($price = isset($_POST['price']) <= $_POST['300,000'])
				{
					print $aline. "</br>";
				}

As for me this piece of code looks like if the price chosen by user is less or equal to 300.000 then print this line with all property details. And when putted into loop it should print all other property details when they meet this if statement.

Hope to hear from you soon ;)

PS. my deadline is monday 10am so i hope that you or anyone could help me to solve at least 3 questions id be happy :) and in the meantime ill get some sleep :)

Edited by infinitus: n/a

1

I would suggest you try breaking the problem down into smaller tasks, for which you then write the code to solve each. So, for your maximum price task you need to:

1. Enter a maximum price and submit the web form.
2. Store the submitted maximum price value in a variable for use later.
3. Read in the properties.txt file one line at a time.
4. Check whether the price of the current line is less than or equal to the maximum price entered.
5. Display the property details if the current line is less than or equal to the maximum price entered.


Now with those tasks in mine I have spotted several mistakes with the code you have posted, but lets work through them in order.

1. Enter a maximum price and submit the web form.
You have written your form code, which posts to maximum.php, so this one is fine.

<html>
<body>
<h4>Estage Agency coursework 1</h4>
<form action ="maximum.php" method ="post">
<select name ="price">
	<option value="100.000">Less then 100.000</option>
	<option value="150.000">Less then 150.000</option>
	<option value="200.000">Less then 200.000</option>
	<option value="250.000">Less then 250.000</option>
	<option value="300.000">Less then 300.000</option>
	<option value="500.000">Less then 500.000</option>
	<option value="750.000">Less then 750.000</option>
</select>
<input type ="submit" />
</form>
</body>

2. Store the submitted maximum price value in a variable for use later.
This is where you made your first mistake. The ternary operator code I submitted previously needs to be used as was, or not at all. Let me try to explain it further:

// This is basically asking, if a price field was found within the submitted form, use it's value, otherwise assume the price value was 100.000
$comparison_price = isset($_POST['price']) ? $_POST['price'] : '100.000';

// This can also be rewritten as follows. This is basically saying, lets assume the price value was 100.000, but if a price field was found within the submitted form, use it's value instead
$comparison_price = '100.000';

if(isset($_POST['price'])
    $comparison_price = $_POST['price'];

So, whichever of the two methods above you use, keep the value in $comparison_price and do not change it.


3. Read in the properties.txt file one line at a time.
You have written code which successfully reads in a text file. It's perhaps not the best solution when working with comma separated values, but it works. I have modified your code slightly to instead return an array of words, rather than doing the comparison within the words function itself.

I have also added in the code to retrieve the selected comparison price after your form was submitted.

// Lets find the comparison price, if specified. Otherwise assume 100.000
$comparison_price = isset($_POST['price']) ? $_POST['price'] : '100.000';

$filename = "properties.txt";
$filepointer = fopen($filename,"r");  // open to read file
$myarray = file ($filename);

for ($mycount = 0; $mycount < count($myarray); $mycount++ )
{
    $aline = $myarray[$mycount];  
    $fields = explode(',', $aline);	
}
fclose ($filepointer);

4. Check whether the price of the current line is less than or equal to the maximum price entered.
This is where you're stuck at the moment. Within the above code, all of the property fields should now be contained within the $fields array.

You have indicated previously that the price is the second value for a particular property, thus based on 0 indexing, the second value will be at index 1 in the array. E.g. 0 => value 1, 1 => value 2.

So lets put together a simple function to compare whether the current property price is less than or equal to the comparison price. This could just as easily be used inline, but we'll put it in a function just incase you need to make it more complicated in the future. This function will simply return true or false, if the property price is less than or equal to the property price.

function compare_price($comparsion_price, $property_price)
{
    return ($property_price <= $comparison_price);
}

5. Display the property details if the current line is less than or equal to the maximum price entered.
Now to put it all together.

// Lets find the comparison price, if specified. Otherwise assume 100.000
$comparison_price = isset($_POST['price']) ? $_POST['price'] : '100.000';

$filename = "properties.txt";
$filepointer = fopen($filename,"r");  // open to read file
$myarray = file ($filename);

for ($mycount = 0; $mycount < count($myarray); $mycount++ )
{
    $aline = $myarray[$mycount];  
    $fields = explode(',', $aline);	

    // Output current property details if price is less than or equal to comparison price 
    if(compare_price($comparison_price, $fields[1]) {
        echo implode('<br />', $fields) . '<br />';
    }
}
fclose ($filepointer);

And that should be it!


You were very close with your various attempts and I think you just needed to take a step back and spend a minute thinking about what it was you are trying to achieve again.

The above code is totally unchecked, so there might be a couple of small mistakes, but hopefully the explanations will be enough to point you in the right direction.

Best,
Rob.

P.S. If it's due Monday at 10am, try not to leave it to the last minute ;)

Edited by blocblue: n/a

0

Thank you Rob i must say the explenation of yours is v good ;D. However i have run into one weird problem

<?php
    // Lets find the comparison price, if specified. Otherwise assume 100.000
    $comparison_price = isset($_POST['price']) ? $_POST['price'] : '100.000';
     
    $filename = "properties.txt";
    $filepointer = fopen($filename,"r"); // open to read file
    $myarray = file ($filename);
     
    for ($mycount = 0; $mycount < count($myarray); $mycount++ )
		{
			$aline = $myarray[$mycount];
			$fields = explode(',', $aline);
     
			// Output current property details if price is less than or equal to comparison price
			if(compare_price($comparison_price, $fields[1])
				{ 
					echo implode('<br />', $fields) . '<br />';
				}
		}
    fclose ($filepointer);
	    function compare_price($comparsion_price, $property_price)
		{
			return ($property_price <= $comparison_price);
		}

?>

When running this code it says that

Parse error: syntax error, unexpected '{' in /var/www/virtual/infinit0s.cba.pl/coursework1/maximum.php on line 16

which means it doesn't know what to do after the IF statement and the character " { " is not recognized ?? why is that ?


EDIT:

if(compare_price($comparison_price, $fields[1])[B])[/B] //<- one ) was missing ;)....
	{ 
	   echo implode('<br />', $fields) . '<br />';
           print $aline. '<br/>';    // this line should print $aline if the IF statement is true?
	}

But the code doesn't display the results.

but when i move the print statement outside IF but keep it within For loop like that

for ($mycount = 0; $mycount < count($myarray); $mycount++ )
		{
			$aline = $myarray[$mycount];
			$fields = explode(',', $aline);
     
			// Output current property details if price is less than or equal to comparison price
			if(compare_price($comparison_price, $fields[1]))
				{ 
					echo implode('<br />', $fields) . '<br />';
					
				}
				print $aline. '<br/>';
		}

It prints the whole properties.txt file instead of the one which should display i.e only properties that meet criteria


www.infinit0s.cba.pl/coursework1/index.html if you click that you will see the code "working" or not

Edited by infinitus: n/a

0

It looks as though you have spaces in your text file after each comma, which a traditional CSV file wouldn't have.

Try replacing the compare_price function with:

function compare_price($comparsion_price, $property_price)
{
    return (trim($property_price) <= $comparison_price);
}

R

0

Ok i have removed spaces from the properties.txt file and i have pasted in that function and still the same result. I tried to move my print statement in and out of the IF statement, and result was that inside IF statement it didn't print anything, and outside but within loop it keeps on printing whole file

2

The problem is the '.' in the prices. Remove them and it should work.

// Lets find the comparison price, if specified. Otherwise assume 250.000
$comparison_price = isset($_POST['price']) ? $_POST['price'] : '250.000';

$filename = "properties.txt";
$filepointer = fopen($filename,"r");  // open to read file
$myarray = file ($filename);

for ($mycount = 0; $mycount < count($myarray); $mycount++ )
{
    $aline = $myarray[$mycount];  
    $fields = explode(',', $aline);	

    // Output current property details if price is less than or equal to comparison price 
    if(compare_price($comparison_price, $fields[1])) {
        echo $aline . '<br />';
    }
}
fclose ($filepointer);


function compare_price($price, $property_price)
{
    $price = str_replace('.', '', $price);
    $property_price = str_replace('.', '', $property_price);

    return (trim($property_price) <= $price);
}
Votes + Comments
Great explanations and helped the OP through to the end. Well done!
good explainer :)! and great help
0

Oh ok now i see :) little annoying thing but i understand it now :) so the " . " was the problem as it was compering 300 to 300,000 so in effect nothing was displayed ! am i right ?

So now i will proceed to questions 3

Edited by infinitus: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.