Jump to content

newbee to PHP, help with setting up my php to send to a txt file


CarriesBack
Go to solution Solved by mac_gyver,

Recommended Posts

This is my code so far, I am a beginner at PHP and my professor is very vague with help. I just want to know in what order in my code should be in when setting up code from a form to send to a text file and if I am doing this correctly. Thanks in advance for any help, I just want to be able to get through this stuff without being so overly confused I make it worse :)
 
 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN"
<head>
<title>Register Bowler</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
 
</head>
<body>
 
<?php
                                                                    
global $errorCount; 
 
if(!isset($_POST['Submit'])){                                                                   //
 
$BowlerName = validateInput(addslashes($_POST['Name']));
$BowlerAge = validateInput(addslashes($_POST['Age']));
$BowlerAverage = validateInput(addslashes($_POST['Average']));
$NewBowler = "$BowlerName, $BowlerAge, $BowlerAverage\r\n";
$BowlersFile = "bowlers.txt";
 
if(is__numeric($BowlerAge)) {
$BowlerAge = round($BowlerAge);
                           }
if(is_numeric($BowlerAverage)){
$BowlerAverage = round($BowlerAverage);
if (($BowlerAverage >= 0) &&
($BowlerAverage <= 300)) {
$retval = $BowlerAverage;
 
}
}
 
   else
   echo "<p>You must enter your Name </p>".
    "<p>You must enter your age. </p>".
    "<p>You must enter your average(enter 0 if you don't have one)</p>"
"<p>Click your browser's Back button to return to the Bowler Registration form and fix these errors. </p>";
 
 
</body>
</html>
 
 
 
 
And this is my form code
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN"
<head>
<title>Bowler Registration Form</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
<style = "text/css">
#body label {padding-left:2px;
margin-left: 10px;
margin-top: 55px;
display:block;
}
#body fieldset {padding-left: 20px;
margin-left: 20px;
  }
#body title {
font-size: 200%;
}
h2 {
    position: absolute;
    left: 100px;
}
</style>
</head>
 
<body>
<h2>Enter your information below to sign up for the tournament!</h2>                                                                   <!-- This is the heading on the page -->
<div id="body">                                                                                                                        <!-- The body of this div is where my form will be placed at -->
<fieldset>
<form name="Bowler Registration" action="RegisterBowlerRusbuldt.php" method="POST">                                                    <!-- This shows the form name, the php file it checks, and how it gets its information -->
<label for="name"> Name :    <input type="text" name="Name " id ="Name" size = "25" /></label>                               <!-- This is the input for the name of the bowler and the type of text it takes -->
<label for="age"> Age   :        <input type="text" name="Age " id = "age" size = "25" /></label>                  <!-- This is for the age of the person signing up on the form -->
<label for="average"> Average :   <input type="text" name="Average " id ="average" size = "25"/></label>                          <!-- This is the bowling average of the person signing up on the form -->
<br>                                                                                                                                   <!-- I added the &nbsp to separate the labels from the boxes so they would line up better-->
<br>                                                                                                 
<input type="submit" value ="Submit" />                                                                                                <!-- This is for the submit button, what it is supposed to do when clicked -->
 
</fieldset>
</form>
</div>
 
<?php
 
$BowlersList = readfile("bowlers.txt");
echo $BowlersList;
 
 
?>
 
 
</body>
</html>

 

Link to comment
Share on other sites

Where did you copy this from? Are you taking credit for this abomination?

 

You begin with html code. Bad move for a PHP script. One should start with the php and finish with the html

 

You start your php code (finally) by asking if the Submit button has been set or not. If not - YOU START LOOKING FOR POST element inputs!!! WHAT?! That's where I stopped.

 

1 - learn what it means to ask the question about whether there is a post present.

2 - learn to check what you have written before asking for help.

3 - If you supposed professor is not being helpful, time to read the textbook and get a manual too! And if you're one of those newbies who say they don't learn well from reading, then I.T. is not in your career path.

Link to comment
Share on other sites

  • Solution
the code on your page should be laid out in this general order - initialization, start of database dependent code, determine user state and permissions, post method form processing, get method business logic, end of database dependent code, get method presentation logic, and html docuement/template.

 

1) initialization - create/define things your code needs - session_start(), require files holding configuration data/function definitions, setup an autoloader for class definitions...

 

2) start of database dependent code - create a database connection.

 

3) determine user state and permissions - check if the current user is logged in and retrieve any permissions the user has. the rest of the code on the page would make use of the logged in state and permissions to determine what code can be ran and what content will be produced.

 

4) post method form processing - the post method form processing code, which causes an action or change in state or change in data values on the server, should come near the start of your file so that you aren't tempted to output anything to the browser before the action/state/or data operation has been performed by the processing code. if your page has multiple sections of form processing code, you would have them all groped together in this section of code.

 

after successfully (no errors) processing any post data, do a header() redirect to the exact same url that the form submitted to. this will cause a get request for your page. this will cause the browser to forget that a form was just submitted to that url and it won't try to resubmit the form data if you refresh the page or browse back to the same url. this also enforces separation of concerns. post method form processing is a separate concern from displaying data due to a get request for your page. if you want to display a one-time 'success' message after the header() redirect, pass it in a session variable, then clear he session variable after the the message gets displayed.

 

if there are errors while processing any post data, you would not redirect, stay on the page, let the rest of the code on the page display the errors, (re)display the form, and repopulate the form fields with (some of) the previously submitted values.

 

5) get method business logic - code that produces/gets data needed for the dynamic content on the page. this code contains any database specific code that knows how to retrieve data from your database tables. the result of this code should be php variables that the code later on the page uses as its input. this code should contain NO html/css/javascript markup.

 

6) end of database dependent code - you can (or let php do this when the script ends/exits) destroy any query result resources (to free up memory) and the database connection at this point since you won't need them any longer.

 

7) get method presentation logic - code that knows how to take the data (database data, errors, form data...) from ALL the above code and produce the dynamic output for the page. if the output doesn't require any 'heavy' processing/formatting, just use the data directly in the html page/template code. the result from this code should be php variables that the html page/template uses. this code should contain NO database specific statements. if your page has multiple sections of get method presentation logic, you would have them all groped together in this section of code.

 

8) html document/template - this section starts with the <!DOCTYPE ... tag and ends with the </html> tag. it is the actual html document that the dynamic output is put into to make the complete page. if you use php (rather than an actual template system) only simple php conditional logic/loops, function calls (that are responsible for producing output), and echo statements should be present in this section of code. any data you output on the page needs to be passed through htmlentities() in order to prevent any html content in it from being operated on by the browser.

 

if you organize the code on your page like this, it will separate all the different concerns, making it easier to see what your code is doing, easier to test, and easier to get help with because you can isolate and post just the relevant part.

 

next, if you put the form processing code and the form on the same page, it will reduce the amount of code you have to produce, since it will eliminate the repetition of the common items. this will also let you re-populate the form field values in the case where there were validation errors with the submitted form data.

 

 

some specific comments for the code you have posted -

 

1) the global keyword only has meaning when used inside of a function (which you are not doing) and even then it should be avoided as it breaks the encapsulation and scope. remove any lines of code containing the global keyword.

 

2) if you use a php array variable to hold validation error messages, it will also serve as an error flag. if the array is empty(), there are no errors. if the array is not empty(), there are errors. after you have validated all the input data, you would use that data if there are not errors. at the point of (re)displaying the form, if there are errors, you would display them, either as a group or display them individually near the form field they go with.

 

3) you should NOT be using addslashes() at all.

 

4) whatever your validateInput() function code is, is probably not actually validating anything. if you want help with the validateInput() code, you need to post it.

 

5) this is a bit tongue in cheek, but a person's age is not a fixed value, unless they are dead, and you should not be storing a person's age. you should be getting and storing the date of birth and then calculating the age when needed.

 

edit: since you are using a file to hold the data, substitute 'file operations' for any mention of 'database' in the above information.

Edited by mac_gyver
Link to comment
Share on other sites

ginerjm ~~ 1. I said I am new to this. 2. No disrespect, but I am doing online schooling for this class and have little to no help from my professor. No, this is not my field of expertise, that is why I am here, to get some help. 3. Thanks for your unhelpful advice.

 

mac_gyver ~~ Thank you. Laying it out in a format like that makes it more understandable to me. It helps knowing how it is supposed to be laid out for me. Again, thank you.

 

For the record, it is two different codes. One for the form and one for the php coding. I have to turn BOTH of them in to my unhelpful professor. 

Link to comment
Share on other sites

If the code you posted is a result of what you are being educated on, you are being seriously taken advantage of. You don't even know how to turn on php mode properly yet. What kind of teaching is that? You blame the professor, I blame the choice of school if that is what they are giving you.

 

If you didn't get it - my response to you should have made you realize how far you are from being any kind of php coder. Don't shoot me because your learning is taking you down the wrong path.

 

Good luck. I do hope you can make significant gains with mac_gyver's extremely detailed writeup. A lot there to digest. :)

Link to comment
Share on other sites

ginerjm ~~ That is what I have for my code thus far, no it isn't everything that I need--I know that. And the problem with the professor is he is on a separate campus than I am, and the course is online, so that does not help. I have been asking for help from all the professors in the department, none know anything about PHP. So I am in need of help, thought I would come here, since you are all experienced at doing this. I really didn't come here to get ridiculed, I have read the book--repeatedly, but when I get to a certain point in my code I get stuck--with NO help. I posted some of the code so that I did so it didn't look like I wanted anyone to answer with the coding that I needed. Sorry for trying to get some help. 

Link to comment
Share on other sites

We aren't averse to helping you out. You just need to read what has been said and start making the changes recommended by us and re-post your 'improved' code. Be sure to read them and follow them because people here don't like to make recommendations and have them totally ignored by someone who can't bother to read and absorb what is being said. Can you show us your current (modified?) code yet?

Link to comment
Share on other sites

Sure. This is where I have gotten to. Just the PHP code. The form part is working fine.

 

 

 

<?php
error_reporting(E_ALL);                                                                                         //This is for error reporting
ini_set('display_errors', 'On');                                                                                //because I want all errors to show  
 
 
if($_POST['formSubmit'] == 'Submit'){                                                                   //This grabs the information from the form
 
$BowlerName = $_POST['Name'];                                                                       //initializing the bowlers name variable
$BowlerAge = $_POST['Age'];                                                                         //initializing the bowlers age variable
$BowlerAverage = $_POST['Average'];                                                                 //initializing the bowlers average variable
 
$errors = array();                                                                                  //this is for error logging
 
if ($BowlerName == ' ') { $errors[] = "You must enter your name ";}                                                    //this is so that if an error is 
if ($BowlerAge == ' ') { $errors[] = "You must enter your age ";}                                           //submitted to any of these values, 
if ((is_numeric($BowlerAverage >= 0)) &&                                                                  //the user can fix them. This makes sure 
($BowlerAverage <= 300)) {                                                                    //the average is within the parameters of 
$retval = $BowlerAverage;                                                                      // 0 and 300
}
if($BowlerAverage == ' ') { $errors[] = "You must enter your average(enter 0 if you don't have one) " ;}
 
$errors[] = "<p>Click your browser's back button to return to the Bowler Registration form and fix these errors. </p>"; //This error message will show up no matter what error shows
 
 
}
else
echo “<p>Thank you for registering! </p>”;                                                           //When all fields are completed correctly        
 
$fp = fopen("$bowlers.txt", "a");                                                                  //This opens the file that will be written to
$savestring = $BowlerName . "," . $BowlerAge . "," . $BowlerAverage . "n";                            //with "a" for appending to the file
fwrite($fp, $savestring);                                                                             //savestring shows information is being saved and 
fclose($fp);                                                                                          //written to the file. Close file
Link to comment
Share on other sites

Your line:

if ((is_numeric($BowlerAverage >= 0)) && //the user can fix them. This makes sure
($BowlerAverage <= 300))
{ //the average is within the parameters of

 

is difficult to follow. Are you testing if the result of a comparison is numeric?

What would make sense would be:

if (!is_numeric($BowlerAverage) || $BowlerAverage <= 0 || $BowlerAverage > 300)
{
(show as error)
}

Note how my code samples here are formatted. When posting code here you should wrap it in "php" and "/php" each in square brackets.

 

Also - just my opinion - but using mixed case in php can become a real PIA since php is case-sensitive. Get used to using all lowercase so that you don't end up having to trade thru your scripts looking a bug caused by the mis-typing of a name somewhere.

 

What is the "n" for at the end of savestring?

Link to comment
Share on other sites

Yes, the bowler average has to be between 0-300, but for each I have to put an error message if that part of the form isn't filled out. If I do it the way you show it, it won't differentiate the errors. "n" at the end of savestring is for new line, or should that be \n? Thanks for the help. 

Link to comment
Share on other sites

No matter what value have for the bowler average, your test will always fail.

 

The expression ($bowleraverage >= 0) is Boolean and therefore not numeric. EG

$bowleraverage = -1;
echo (is_numeric($bowleraverage >= 0)) ? 'OK' : 'Error' . '<br>';

$bowleraverage = 0;
echo (is_numeric($bowleraverage >= 0)) ? 'OK' : 'Error' . '<br>';

$bowleraverage = 50;
echo (is_numeric($bowleraverage >= 0)) ? 'OK' : 'Error' . '<br>';

That code outputs

Error
Error
Error

You need to separate the is_numeric() check from the value checks as ginerjm said.

Edited by Barand
Link to comment
Share on other sites

Do you have access to the online PHP Manual? That would be a good place to lookup how to use these functions instead of just throwing code together that can't possibly function properly.

 

The is_numeric function as the manual would say gives you a true/false response when you test a single value. You can't combine that with anything else, which is what you are writing. The manual would show you (I think) examples of how to use that function and many other functions.

 

The link: http://www.php.net/manual/en/funcref.php

Link to comment
Share on other sites

ginerjm ~~ I do. Worst setup ever to try to figure something out. 

 

Barand ~~ Thanks. I will try that. 

 

From instructions:

 

 Validate the inputs that all three fields are required and the age must be a positive integer number, the average must be greater than 0 and less than 300.

Link to comment
Share on other sites

With guidance this is how far I've gotten. Thanks for the help~~~Still getting an error for one of the "else" statements though

 

<?php
error_reporting(E_ALL);                                                                                         //This is for error reporting
ini_set('display_errors', 'On');                                                                                //because I want all errors to show  
 
 
if($_POST['formSubmit'] == 'Submit')  {                                                                 //This grabs the information from the form
 
        
 
 
                                                                                                                                
 
if (empty($_POST['Name']))                                                                                    //This is in case the user doesn't input a name
$errors .= "<p>You must enter your name </p>\n";                                                          //This displays the error to the user
                                                                                                 
if (empty($_POST['Age']))                                                                                 //This is in case the user doesn't input an age
$errors .= "<p>You must enter your age </p>\n"                                                            //This displays the error to the user
else (!is_numeric($_POST['Age']))                                                                         //This makes sure the age is numeric
$errors .= "<p>Your age must be a whole number </p>\n";                                                   //This displays that the number is not in correct format
                                                   
if ((empty($_POST['Average']))                                                                                                           //This is in case the average post is empty or doesn't
   $errors .= "<p>You must enter your average(enter 0 if you don't have one) </p>\n";                        //show a value between 0 and 300==error displays        
else if ( is_numeric($_POST['Average'])) && ($_POST['Average'] > 0 && $_POST['Average'] <= 300 ))
else 
echo"<p>Thank you for registering! " ;                                                                     //This displays if it makes it through everything
}
$errors = "<p>Click your browser''s back button to return to the Bowler Registration form and fix these errors. </p>";   //This displays on all errors
 
 
 
 
 
?>
 
<?php
 
if(isset($_POST['Name']) && is_numeric($_POST['Age']) && is_numeric($_POST['Average'])) {                           //to bring in the values of each items going into file 
$data = $_POST['Name'] . '-' . $_POST['Age'] . '-' . $_POST['Average'] . "\n";                                      //These end up in variable data
                                                                                         
            $ret = file_put_contents(' /wamp64/www/bowlers.txt', $data, FILE_APPEND | LOCK_EX);                            //The contents of data, go into bowlers.txt and the file is appended and locked
                                                                 
    if($ret == false)                                                                                              //if the return is false, then the file is not written to
die('There was an error writing to file');
               
else                                                                
echo "$ret written to file";                                                                                //Otherwise the file has been written 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.