Solved

PHP Sort & Delete

Posted on 2014-10-26
27
1,149 Views
Last Modified: 2014-10-27
Hi,  
My page is at:  http://webwirepublishing.com/contact.html
I am trying to get the names to sort and delete duplicates with user input (button) and it does not work.  Can you take a look at the script?  It is inside an Iframe
HTML:  
<div id'"frameHolder">
            <IFRAME src="GuestBook.php" width="200" height="750" style="border: 2px solid #333; width: 750px; height: 750px; "><A href="GuestBook.php" target="new" style="color:darkred">Click here to see the latest quotes </A>
                    </IFRAME></div><!-- end frameHolder div  --!>
PHP:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<!-- Deanna L. Andru, October 1, 2014  CURRENT-->
<html>
      <head>        
            <meta charset="UTF-8">
                 <title>Guest Book CURRENT</title>
    </head>
           <body>                                                                            
<?php
      if (isset($_POST['submit'])) {
      $firstName = stripslashes($_POST['first_name']);
    $lastName = stripslashes($_POST['last_name']);
    $wholeName = $firstName . ' ' . ($lastName);
      $guestRecord = "$wholeName\n";
    $guestBook = fopen("guestbook.txt", "ab");
         if ($guestBook === FALSE)          
               echo "There was an error saving your name!";      
         else {  
               fwrite($guestBook, $guestRecord);          
                     fclose($guestBook);    
                           echo "<strong>Your entry has been saved. Current Guest List:</strong>.";      
         }
      }
// if info then process
if (isset($_GET['submit'])) {
       if ((file_exists("guestbook.txt")) && (filesize("guestbook.txt") != 0)) {
            $guestArray = file("guestbook.txt");
               //switch to $_Get Method
            switch ($_GET['action']) {                      
               // remove duplicate entries
 case 'Remove Duplicates':
      $guestArray = array_unique($guestArray);
      $guestArray = array_values($guestArray);
      break;
case 'Sort Ascending':
      sort($guestArray);
      break;
      }            
    //count to see how many entries there are              
      if (count($guestArray)>0) {
          $newGuest = implode($guestArray);
        $guestStore = fopen("guestbook.txt", "ab");  
                  if ($guestStore === false)
                        echo "There was an error updating the message file";                
                  else {fwrite($guestStore, $newGuest);
                        fclose($guestStore);
            }          
      }          
    else
       unlink("guestbook.txt");}
}
    if ((!file_exists("guestbook.txt")) || (filesize("guestbook.txt") == 0))      
          echo "<p>There are no entries.</p>";
    else {
        // txt file empty show an error                                
        if ((!file_exists("guestbook.txt")) || (filesize("guestbook.txt") == 0))      
        echo "<p>There are no entries.</p>"; else {
              //if array exists display the txt file in a table      
              $guestArray = file("guestbook.txt");      
                    echo "<table style=\"background-color:white\" border=\"0\" width=\"75%\">";      
 //count number of guest names
$count = count($guestArray);      
      for ($i = 0; $i < $count; ++$i) {
        $currMsg = explode("~", $guestArray[$i]);      
// TABLE to display results:
                echo "<td width=\"95%\"><span style=\"font-weight:bold\"></span>" . htmlentities($currMsg[0]);    
                echo "</tr>\n";
    }      
    echo "</table>";
  }
}
?>
<p>
<a href="GuestBook.php?action=Sort%20Ascending">Sort Names</a><br />
<a href="GuestBook.php?action=Remove%20Duplicates">Delete Duplicate Names</a><br />
</p>
<h2>Guest Book</h2> <hr>      
      <form method="POST" action ="GuestBook.php">                            
               <p>First Name<input type ="text" name="first_name"/><p>Last Name<input type ="text" name="last_name"/><br /></p>
        <p><input type="submit" name="submit"value="Sign the Guest Book" /><input type="reset" name="reset" value="Clear Form" /></p></form><hr>  
</body></html>

this writes to a text file guestbook.txt
0
Comment
Question by:Deanna Andru
  • 17
  • 8
27 Comments
 
LVL 58

Expert Comment

by:Gary
ID: 40405355
$guestArray is just the contents of guestbook.txt - it is not an array but you are treating it as if it was
0
 

Author Comment

by:Deanna Andru
ID: 40405367
how so?
0
 
LVL 58

Expert Comment

by:Gary
ID: 40405371
Well that rather depends on what is in the file.
The code is all over the place.
0
 

Author Comment

by:Deanna Andru
ID: 40405373
case 'Remove Duplicates':      
            $guestArray = array_unique($guestRecord);      
            $guestArray = array_values($guestRecord);      
            break;
            //sort ascending
              case 'Sort Ascending':
              $guestArray = sort($guestArray);
                    break;  
               //sort Decending
              case 'Sort Decending':
              $guestArray = ksort($guestArray);
              break;                              
                 }            ?
0
 

Author Comment

by:Deanna Andru
ID: 40405375
My code is in 2 files, but Guestbook.php is supported byt guestbook.txt.  I guess it was unnecessary to add the page it will be accessed from.

Here is the entire GuestBook.php file again after minor change but still not working:
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<!-- Deanna L. Andru, October 1, 2014  CURRENT-->
<html>
	<head>        
		<meta charset="UTF-8">
     		<title>Guest Book CURRENT</title>
    </head>
     	<body>                                                                            
<?php
      if (isset($_POST['submit'])) {
	$firstName = stripslashes($_POST['first_name']);
    $lastName = stripslashes($_POST['last_name']); 
    $wholeName = $firstName . ' ' . ($lastName);
	$guestRecord = "$wholeName\n";
    $guestBook = fopen("guestbook.txt", "ab"); 
         if ($guestBook === FALSE)           
         	echo "There was an error saving your name!";      
         else {  
         	fwrite($guestBook, $guestRecord);           
         		fclose($guestBook);    
         			echo "<strong>Your entry has been saved. Current Guest List:</strong>.";      
         } 
	} 
// if info then process
if (isset($_GET['submit'])) {
 	if ((file_exists("guestbook.txt")) && (filesize("guestbook.txt") != 0)) {
		$guestArray = file("guestbook.txt");
         	//switch to $_Get Method 
            switch ($_GET['action']) {                       
               // remove duplicate entries
case 'Remove Duplicates':      
            $guestArray = array_unique($guestRecord);      
            $guestArray = array_values($guestRecord);      
            break;
            //sort ascending
              case 'Sort Ascending':
              $guestArray = sort($guestArray);
                    break;  
               //sort Decending
              case 'Sort Decending':
              $guestArray = ksort($guestArray);
              break;                              
                 }            
    //count to see how many entries there are              
	if (count($guestArray)>0) {
    	$newGuest = implode($guestArray); 
        $guestStore = fopen("guestbook.txt", "ab");  
                  if ($guestStore === false)
                  	echo "There was an error updating the message file";                
                  else {fwrite($guestStore, $newGuest);
                  	fclose($guestStore);
		}           
	}           
    else
       unlink("guestbook.txt");} 
} 
    if ((!file_exists("guestbook.txt")) || (filesize("guestbook.txt") == 0))      
    	echo "<p>There are no entries.</p>"; 
    else {
        // txt file empty show an error                                
        if ((!file_exists("guestbook.txt")) || (filesize("guestbook.txt") == 0))      
        echo "<p>There are no entries.</p>"; else {
        	//if array exists display the txt file in a table       
        	$guestArray = file("guestbook.txt");      
        		echo "<table style=\"background-color:white\" border=\"0\" width=\"75%\">";      
 //count number of guest names
$count = count($guestArray);      
	for ($i = 0; $i < $count; ++$i) {
        $currMsg = explode("~", $guestArray[$i]);      
// TABLE to display results:
    		echo "<td width=\"95%\"><span style=\"font-weight:bold\"></span>" . htmlentities($currMsg[0]);    
    		echo "</tr>\n"; 
    }      
    echo "</table>";
  }
}
?>
<p>
<a href="GuestBook.php?action=Sort%20Ascending">Sort Names</a><br />
<a href="GuestBook.php?action=Remove%20Duplicates">Delete Duplicate Names</a><br />
</p>
<h2>Guest Book</h2> <hr>      
	<form method="POST" action ="GuestBook.php">                            
   		<p>First Name<input type ="text" name="first_name"/><p>Last Name<input type ="text" name="last_name"/><br /></p> 
        <p><input type="submit" name="submit"value="Sign the Guest Book" /><input type="reset" name="reset" value="Clear Form" /></p></form><hr>   
</body></html>

Open in new window

Ed. note: Code moved into code snippet.
0
 

Author Comment

by:Deanna Andru
ID: 40405376
0
 
LVL 58

Expert Comment

by:Gary
ID: 40405378
What is that link supposed to be?
0
 

Author Comment

by:Deanna Andru
ID: 40405383
that is the .php page inside the iFrame on the contact.html page.
0
 

Author Comment

by:Deanna Andru
ID: 40405384
Where the code is located.
0
 

Author Comment

by:Deanna Andru
ID: 40405387
I am doing this for a class final project.   PHP
0
 
LVL 58

Expert Comment

by:Gary
ID: 40405391
You've already posted the code.
No one is going to going to give you an answer here, we don't help with school work only give pointers.

You have a file that you need to place in an array so have a look at

http://www.w3schools.com/php/php_arrays.asp

http://php.net/manual/en/language.types.array.php
0
 

Author Comment

by:Deanna Andru
ID: 40405403
Yes this is partially for a final project, as you can see it is for a portfolio.  I was not advised by the sales team that you would not help with tutoring when necessary.  That is why I am here.  Instruction that is clear would be helpful, pointers are found in the textbook.  Thank you.
0
 

Author Comment

by:Deanna Andru
ID: 40405408
I am not seeing this:

"Please use the code snippet when you want to share code with others here at EE.  It's activated by clicking on Code in the text area header.  When you do that you will get a pair of "code" tags and the cursor will be positioned in the exact location for a "paste" operation.  Advantages: We get a unispace font that is easier to read and we get line numbers that facilitate discussion.  Thanks! "
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 58

Expert Comment

by:Gary
ID: 40405411
We'll give you clues and tips if you are stuck on something - we're not going to write the code for you - that's academic dishonesty and what you should be learning in class.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 40405426
The general design of any WWW request starts with the question, "Is this request idempotent?"  If the answer is "yes" the correct request method is GET; otherwise the request is almost certainly made via POST.  When you have a script that can perform two different actions, one idempotent and one not idempotent, it's best to separate the scripts so you can choose GET or POST but not both in the same script.

PHP scripts can produce more than one HTML document.  For example, a single PHP script can produce an HTML form and can process the request from that HTML form.  In my experience it's often a good design to consolidate form scripts and action scripts into a single script file.

You're headed in the right direction to use array_unique() to remove duplicates.  A design strategy might be to read the guestbook into an array with file() then apply array_unique().  After that is done, the duplicates are eliminated and you can use implode(PHP_EOL) to reconstruct the array into a string for data storage.  You can rewrite the de-duplicated file with file_put_contents().

Regarding sorting the data, PHP has several sorting functions.  Like all other PHP functions these are documented in the online man pages.  You can find the comparison here:
http://php.net/manual/en/array.sorting.php

If you're new to PHP and want some learning resources, this article can help.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

Best of luck with your project, ~Ray
0
 

Author Comment

by:Deanna Andru
ID: 40405453
Ok, well thank you for the pointers.  I will be playing with it some more based on your helpful information.
0
 

Author Comment

by:Deanna Andru
ID: 40405467
I've requested that this question be closed as follows:

Accepted answer: 0 points for Deanna Andru's comment #a40405453

for the following reason:

Not sure yet.
0
 

Author Comment

by:Deanna Andru
ID: 40405458
Is it academic dishonesty to use textbook material in a final project?
0
 
LVL 58

Expert Comment

by:Gary
ID: 40405468
Question should be deleted.
0
 

Author Comment

by:Deanna Andru
ID: 40405475
I've requested that this question be deleted for the following reason:

embarrassing to be accused of academic dishonesty when asking for assistance with a final class project using textbook code.  I would like my profile to be removed as well.  Please delete my account.  
0
 

Author Closing Comment

by:Deanna Andru
ID: 40405476
Very professional and pointed in the right direction.
0
 
LVL 58

Expert Comment

by:Gary
ID: 40405477
No one accused you, I said we won't help with cheating only give pointers.
0
 

Author Comment

by:Deanna Andru
ID: 40405483
I think you have already mentioned that to me on other questions.  I understand, just seeking assistance.  Pointers are good.  I am taking PHP, SQL and JavaScript and thought I might get some assistance here.  I would like to solve the issue so signing off .  Thank you.
0
 

Author Comment

by:Deanna Andru
ID: 40405614
I got it working.  I started from scratch, the code was all jumbled.  The instructions in the book are not always clear (do I add that snippet in or after the last bracket is my concern).  I also used the message board code from our chapter 6 assignment, it seems to work.    Your pointers are good, they have helped me in the past and I thank you.  This is not a class "assignment" it is the  "final project" for PHP, SQL and Javascript.  I am really stressed with these three online classes with little or no one-on-one.   So any feedback or comments that might point me in the right direction is good.  I don't think I am a programmer, but I am a designer and can usually "make things work" as you can see from the portfolio, but I am just beginning to understand how it all fits together and have too much to process at the moment.   The main goal is to get the code to work live on the server.  Honestly, I can figure it all out and process it later.  I am just soaking it in.  After this, I think I will stick to design.  :-)  "Not a code monkey"
0
 
LVL 58

Expert Comment

by:Gary
ID: 40405624
If your tutor is working from old books and recommending them to you then he really is not a good tutor at all - I had the same thing a few years ago in a recognised college when I wanted to get to grips with some skills and couldn't believe the tutor was teaching methodology from 3 years previous, I think I knew more than she did - the web is a very fluid and you have to be on top of it all the time which means learning all the time.
Books can be used as a basis for learning the basics but usually they are out of date by the time they go to print.
There are numerous online courses for learning that are more current with the standards.
0
 

Author Comment

by:Deanna Andru
ID: 40406505
It is what it is, I don't have a tutor and taking online classes.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now