Newbie to programming needs guidance

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

dagee
Forum Commoner
Posts: 33
Joined: Thu Oct 19, 2006 8:31 pm

Newbie to programming needs guidance

Post by dagee »

Everah | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I hope this question is not too basic but I have been working on this script for work (I am a math teacher not a programmer - as you will be able to easily spot from my code.)

Basically here is what the scipt does.  On a form webpage, the user supplies some data.  On a second page (the php page that I am struggling with) the script opens up a text file and looks to see if that data has already been entered.  If so it prints out a warning message.  The problem is that when I compare each line in the text file with the user input the script cannot recognize when both pieces of information are the same.  I am obviously not grasping something mentally (no surpise there).  Please, what am I missing:

Thank you so much in advance for any guidance.  Also please do realize I am really, really very new to this whole programming thing - be gentle 

code: (I just pulled out the part where the error is occuring)

Code: Select all

$fileName = "carts.txt";
		$fp = fopen($fileName, "r");
		$line = fgets($fp);
		//$testLine = trim($line);
		
		//store data in variables
		$name = trim($_POST['name']);
		$cart = trim($_POST['cart']);
		$month =trim($_POST['month']);
		$tenDay= trim($_POST['tenDay']);
		$oneDay= trim($_POST['oneDay']);
		$data=$name.$cart.$month.$tenDay.$oneDay;
		$InputData=$data. "\n";
		$n = 0; // counter
		 
		while (!feof($fp))
		{
			$line = fgets($fp);
		
			
			if ("$line" == "$data")  // This is where the problem is. The program keeps going to the else part of this statement even though the information that is exactly the same.
			{
				print "Somone has already checked out this cart";
			}
			else
			{
				print "$data <br />";
				print "$line"; 
                     }
              }
code cut off here


Everah | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

you need to assign an id to the cart... that way you can just check the id instead of all that...
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

I believe you accidentally posted a new thread when you meant to just reply in this one... but to answer your question... I'll need to ask a question.

How are the carts generated?

If you have the ability to change the way the carts are generated, when you generate them, assign each one a unique id... that way, when you need to check if one exists, you can just check to see if the id already exists... no fiddling around with all that stuff you're doing.
dagee
Forum Commoner
Posts: 33
Joined: Thu Oct 19, 2006 8:31 pm

Carts generated

Post by dagee »

That's a really good question. To answer the question let me back up a bit. Here is the situation: At my school (my work) there are about 15 computer carts that teachers check out for particular days. What I am trying to do is write a php script that lets teachers reserve a specific cart for a specfic day. Basically what happens is that the teacher enters their name, cart number and date they want the cart. That info is saved to a text file. When I do the comparison I want to compare the cart # and the date data pieces to the new ones entered by the user (I hope that makes sense).
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

would you mind posting carts.txt so I can see how the data is formatted?
dagee
Forum Commoner
Posts: 33
Joined: Thu Oct 19, 2006 8:31 pm

carts.txt

Post by dagee »

Here is the contents of the text file.

dagANovember12
dagANovember12
dagANovember12
dagANovember12
dagANovember12
dagANovember12
dagANovember12
dagANovember12
dagANovember12
dagANovember12
dagANovember12
dagANovember12
dagANovember12
dagANovember12
DagASeptember00
DagASeptember00
DagASeptember00
DagASeptember00
DagASeptember00
DagASeptember00
DagASeptember00
DagASeptember00
DagASeptember00
DagASeptember00
DagASeptember00
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Have you considered setting up a MySQL database for this project?
dagee
Forum Commoner
Posts: 33
Joined: Thu Oct 19, 2006 8:31 pm

Post by dagee »

I have not just because I have just learned how to write to a text file. Is there a big advantage to using the Mysql database. I am sure I could learn it if needed.

The reason I chose a text file is because I have experience using a text file to store data
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Imagine running a database query to check if the record ID is in it:

Code: Select all

<?php
// This is a cheap example, but you kind of get the drift I hope
$sql = "SELECT COUNT(`id`) AS row_count FROM `mytable` WHERE `subject` LIKE '%$subject%'";
if (!$result = mysql_query($sql))
{
    die('Could not run the query: ' . mysql_error());
}

$row = mysql_fetch_array($result);
if ($row['row_count'] != 1)
{
    // It is not in there
}
else
{
    //it is
}
?>
Of course there are other ways to do it, including using a text file. It just seems more extensible, expeciialy if there is a chance that you will be making relationships in the data or expanding your application.
Last edited by RobertGonzalez on Thu Oct 19, 2006 11:26 pm, edited 2 times in total.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Imagine running a database query to check if the record ID is in it:

Code: Select all

<%ACphp
// This is a cheap example, but you kind of get the drift I hope
$sql = "SELECT COUNT(`id`) AS row_count FROM `mytable` WHERE `subject` LIKE '%$subject%';
if (!$result = mysql_query($sql))
{
    die('Could not run the query: ' . mysql_error());
}

$row = mysql_fetch_array($result);
if ($row['row_count'] != 1)
{
    // It is not in there
}
else
{
    //it is
}
%AC>
Of course there are other ways to do it, including using a text file. It just seems more extensible, expeciialy if there is a chance that you will be making relationships in the data or expanding your application.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

I'm still not entirely sure what you are trying to do, but I hope this helps... it doesn't solve the problem, because like I said I'm not sure what it is... (the data confused me even more hehe). But hopefully this can give some inspiration

Code: Select all

<?php
$fileName = "carts.txt";

$carts = array();

/* you need to check that these exist before you try to use them... what I've done here is test if they are set,
   and if so, assign their value to the variable, otherwise, assign a null value */
$name   = isset($_POST['name']) ? trim($_POST['name']) : null;
$cart   = isset($_POST['name']) ? trim($_POST['cart']) : null;
$month  = isset($_POST['name']) ? trim($_POST['month']) : null;
$tenDay = isset($_POST['name']) ? trim($_POST['tenDay']) : null;
$oneDay = isset($_POST['name']) ? trim($_POST['oneDay']) : null;

/* Now... I would format your data more like this...
dag|A|November|01
dag|A|November|15
dag|A|November|13
dag|A|November|03
dag|A|November|30
dag|A|November|26
dag|A|November|17
dag|A|November|29
dag|A|November|22
dag|A|November|20
dag|A|November|04
dag|A|November|11
dag|A|November|16

This way you may access each piece of information more easily... */

$data = file_get_contents($fileName);
$carts = explode("\n", $data);
foreach($carts as $cart){
	// Look up explode() on php.net... it's a lifesaver when it comes to working with text files
	$cart_data = explode("|", $cart);
	echo "First value: " . $cart_data[0] . "<br>";
	echo "Second value" . $cart_data[1] . "<br>";
	echo "Month: " . $cart_data[2] . "<br>";
	echo "Day: " . $cart_data[3] . "<br><br>";
	/* Outputs this:
	First value: dag
	Second valueA
	Month: November
	Day: 04 */
}
?>
User avatar
Cameri
Forum Commoner
Posts: 87
Joined: Tue Apr 12, 2005 4:12 pm
Location: Santo Domingo, Dominican Republic

Post by Cameri »

Well, first, we have a problem that requires a bit of logic, if you save each line with the name of a teacher for a specific date, if another teacher with a different name tries to check out that cart with the same date information, he will get that no cart for that day exists (that's what your code is kind of like, doing), that's because the name of the teachers are different, thus, the "cart lines" you are generating are different, thus, you are not able to find out if it's being check out again.

There are several solutions to your problem, you could add all the $_POST vars into an array, serialize() it, and then store THAT line, and then when you want to check if the cart is checked out already, just read through the file again, line by line, just like you are doing, but each line, you must remove the ending \n with trim(), then you unserialize() it, compare JUST the date information, and then, if the conditions are met take the appropiate action.

To store the cart reservation:

Code: Select all

/*no data validation in the code, supposing we rely on user supplying valid data! */
$store_cart = true; //wether or not to store the cart, could change if cart/date is taken

$name = trim($_POST['name']);
$cart = trim($_POST['cart']);
//...
$date = trim($_POST['date']);

$cart_array = array(
  'name'  => $name,
  'cart'  => $cart,
  //...
  'date' => $date
);

$file = file("carts.txt"); //get the file as an array
foreach($file as $line){
 $myline = trim($line); //remove any spaces
 $current_cart = unserialize($myline); //unserialize the string and get the stored cart array
 if ($current_cart['date']==$cart_array['date'] && $current_cart['cart']==$cart_array['cart'])
  $store_cart = false;
}

if ($store_cart) {
  $cart_string = serialize($cart_array);
  $cart_string .= "\n"; //append a newline character

  //store $cart_string in carts.txt in a new line using
  $fp = fopen("carts.txt","a");
  if ($fp) {
   echo "Successfully reserved the cart\n";
   fwrite($fp,$cart_string);
   fclose($fp);
  } else {
   echo "Error storing cart!\n";
  }
} else {
 echo "Cart already taken!\n";
}
dagee
Forum Commoner
Posts: 33
Joined: Thu Oct 19, 2006 8:31 pm

Post by dagee »

Actually I had not yet changed the name part. I was going to take that out in the comparision. So in my tests I always used the same name. When I had php print out what each part of the if statement was comparing they looked exactly the same. I am assuming that perhaps they were different data types which is why php was not returning what I wanted (like one was an array and the other was a string).

Newbie question again. Is each element a string? Or something different?

By the way Cameri, I like how you just whipped that out in a few minutes. I have been working on that particular part for hours.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Stay at it dagee. You'll find that the more common code snippets are the ones that start to come a lot faster as you develop more.
dagee
Forum Commoner
Posts: 33
Joined: Thu Oct 19, 2006 8:31 pm

Post by dagee »

By the way, I cannot tell you guys how awesome you are. The fact that you all just helped me like that is really cool of you. I am going to look at Cameri's code, and use it to fix mine. the Mysql stuff is still way out of my league
Post Reply