Jump to content

Check for existing entries.


ZombieToast

Recommended Posts

I'm a beginner working with Don Gosselin's PHP Programming With MySQL and I was hoping someone could help me out a little with a certain case file (7-1 on page 361 for anyone who has the book).  I've been catching onto all of this stuff without much trouble, but I seem to have caught a snag here.  This particular case file wants me to create a guestbook that collects users' names and e-mail addresses, checks for existing names, removes duplicate entries, and displays the information in alphabetical order.  That sounds pretty simple, but it's just not working out for me.  My problem is that I can't get the script to check for existing names and alert the user if the name already exists.

 

Right now, I have a $NameExists variable set to a value of FALSE.  An if statements checks to make sure the .txt file exists, and if it does, it loads the file into an array (theoretically at least).  Then I'm trying to make a for loop check the array for any instances of the user-entered name.  When found, it changes $NameExists to TRUE.  Another if statements checks to see if $NameExists is true, and if so, it displays an error message.  Otherwise, the script executes normally and lets the information submit.

 

While going through a similar exercise in the chapter, it worked out just fine.  However, when I try it out on my own, it doesn't work at all.  It would appear that the first if statement isn't working and $NameExists is maintaining its FALSE value because when I manually change it to TRUE, the script works.  Any suggestions?  The posting guidelines said to refrain from posting codes/scripts, so I'll obide to that unless anyone wants to see what I have.  I'm still learning this stuff, so I don't know if I'm completely off-track or if I'm using improper syntax or what.  Anyway, any help/suggestions would be appreciated.

Link to comment
Share on other sites

im sure it said refrain fomr posting large scripts, and try to post the "relevent" code if needed :P

 

anyway i believe we will need this if statement and some surrounding code, if its a small file (less than 100 lines or so) then post it all i at least will take a look im sure other will too :P

 

also a good problem solution is debugging, echo out variables you are comparing and see if it is what it should be etc, print_r should be used to print entire arrays (look at source html ouput for a neat representation when using print_r)

Link to comment
Share on other sites

Thanks for taking a look.  My script is relatively small; I just wanted to be cautious because I know some people can be pretty picky about rules.  Heh.  I'm still a beginner, so try to go easy on me if I've got this completely wrong and have blasphemed and spit in the face of all programmers...

 

if (empty($_GET['fname']) || empty($_GET['lname']) || empty($_GET['email']))
   echo "<p>You must fill out all fields!  Click your browser's Back button to return to the form.</p>";
else {
   $NameExists = FALSE;
   if (file_exists("lab7guestbook.txt") && filesize("lab7guestbook.txt") > 0) {
      $MessageArray = file("lab7guestbook.txt");
      for ($i=0; $i<count($MessageArray); ++$i) {
         $CurMessage = explode("~", $MessageArray[$i]);
         if (in_array($_GET['fname'], $CurMessage)) {
            $NameExists = TRUE;
            break;
         }
      }
   }

   if ($NameExists)
      echo "<p>You've already signed the guestbook!</p>";
   else {
      $FirstName = addslashes($_GET['fname']);
      $LastName = addslashes($_GET['lname']);
      $Email = addslashes($_GET['email']);
      $GuestBook = fopen("lab7guestbook.txt", "a");
      if (is_writable("lab7guestbook.txt")) {
         if (fwrite($GuestBook, $LastName . ", " . $FirstName . " (" . $Email . ")" . "\r\n"))
            echo "<p>Thank you for signing our guestbook!</p>";
         else
            echo "<p>Cannot add your name to the guestbook.</p>";
      }
      else
         echo "<p>Cannot write to the file.</p>";
      fclose($GuestBook);
   }
}

 

The code starts off by checking verifying that the fname (first name), lname (last name), and email fields are all filled out.  It then tries to check whether or not a name exists (I'm currently using $_GET['fname'] to try to test this).  The last section then processes the data.  This script is very similar to the one from the tutorial...of course, that could be what's messing me up.  Thanks again to anyone willing to take a look at this.  I've got to head over to my girlfriend's house, but I'll be working on this and checking back periodically while I'm there.

Link to comment
Share on other sites

which if statements is not working? the is_empty()'s?

 

personally i would never use if ($NameExists), i would use if ($NameExists == True)

 

 

also increments works like so:

$i++;

----------------

i would highly reccommend -not- using flat file db, though i suppose the knowledge is useful for the How-To, MySQL is much easier/efficient/effective

 

hope this helps,

Link to comment
Share on other sites

Thanks for your comments; I'll update my code using your suggestion.  If how the book has been going up until now is any indication, I'm sure more effective methods are on their way.  Typically, it'll teach me all about a certain method and gradually introduce me to several other methods, each one more useful and effective than the last.  This is basically just an introduction to reading from and writing to files in a database, as well as manipulating arrays.  If I can't comprehend this fully, then I'm afraid I might have even more problems later on.

 

The if statement that is giving me trouble is the file_exists (line 5).  It isn't returning a value of TRUE when a field value (fname) already exists.  I'm pretty sure the $_GET['fname'] (line 9) is related to the problem.  If I replace it with $MessageArray[1], I get a value of TRUE.  Of course, this will give me a value of TRUE no matter what is entered because it merely checks to see if a key exists in that position.

 

I'm not sure if I'm making any sense with that.  Basically, I think I'm either incorrectly loading the info into an array or I'm not exploding the array properly.  But I'm really not sure because the concept is a bit unclear to me.  What I need the script to do is check the values of $MessageArray[0] and $MessageArray[1].  Then if they contain the values of $_GET['lname'] and $_GET['fname'], $NameExists will become TRUE.

 

I hope you get what I'm saying 'cause honestly, I'm starting to confuse myself.  Ha.

Link to comment
Share on other sites

Just for the heck of it, I tried print_r($CurMessage); and it displayed this...

 

Array ( [0] => lname, fname (email) )

 

But if I understand correctly, it should be:

 

Array ( [0] => lname [1] => fname [2] => email )

 

This gives me the impression that my field values aren't being read into the array properly because they're all being entered as one key instead of three. Of course, I don't know if I'm right and if I am, I'm not exactly sure how to fix this. Heh. If you have any input, I'd greatly appreciate it. For now, I must finally go to bed.

Link to comment
Share on other sites

this line:          $CurMessage = explode("~", $MessageArray[$i]); explode a string into an array that you want:

 

eg: string~string~string would become:

 

Array (
   [0] => "string"
   [1] => "string"
   [2] => "string"
)

 

unfortunately the strings your trying to explode dont use ~ they use , (comma) and brackets (email) so:

 

either; change the strings in the db to: string~string~string OR:

 

Change the explode function to a preg_match function like so:

 

preg_match("/(.+),(.+)(\(.+\))/i",$MessageArray[$i],$matches); then $matches would become $CurMessage.

Note: (REGEX might not work - untested).

 

i doubt you will know about regex early on in your book but its an extremely useful part of php.

 

 

hope this helps,

Link to comment
Share on other sites

Thanks a bunch for the help.  I can't believe I didn't notice how I was separating the strings.  I changed my fwrite so it would use tildes and now the script works just fine.  When I tried using preg_match, it didn't change anything, but I'm not familiar with it, so I probably didn't do it right.  As for regex...I was introduced to it in a JavaScript class, but that was awhile ago and we only touched on it briefly, so I'm not exactly well-versed on the matter.

 

Anyway...the tildes make my script work, but when I display the entries on another page, they now show up as "LastName~FirstName~Email" when I use the following script...

 

<?php

$GuestBook = fopen("lab7guestbook.txt", "r");

if ($GuestBook) {
while (!feof($GuestBook)) {
	$Visitor = fgets($GuestBook);
	$Visitor = stripslashes($Visitor);
	echo "<p>$Visitor</p>";
}
echo "<p>Thank you!</p>";
}
fclose($GuestBook);

?>

 

I could just change the separators to commas instead of tildes and be done with the whole thing, but for my own personal knowledge, I'm wondering how I could modify the above code to get the strings to display in the "LastName, FirstName (Email)" format.  These arrays are being a bit trickier than what I'm used to.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.