Jump to content

Taking form data directly to an array?


fema3

Recommended Posts

Hey guys and gals,

 

I'm new at coding, and I'm having some difficulty figuring out what might be the problem. 

 

In words, I'm taking a few text boxes from a html form (such as the user enters a couple of numbers) and put that directly into an array in php.

 

Essentially it is this:

 

<input type="text" name="height[]" id="height[]" required="required">

<input type="text" name="weight[]" id="weight[]" required="required">

 

a submit button takes the data via post to the calculate.php.

 

There we have

$height = $_POST['height'];

$weight = $_POST['weight'];

 

 

print_r($height);

 

So what is going on is that when the user submits , say 55 in the height and 25 in the weight.  It as expected gets loaded into the $height and $weight arrays.  But when I try to add a new height and weight to the array via a new submit, say 22 and 95, the old values get replaced by the new ones, instead of adding to the $height and $weight array. 

 

So it always looks like

array[0] => 55

array[0] => 22

 

What I want it to do is to increment,

array[0] => 55, array[1] => 22 ...

 

I check the data coming from POST, it seems to be a string, is it because the array should be numeric and the data coming into the array are strings? 

 

My thoughts are that the data from post are being put into a variable, but I just don't think this is right. 

 

Thanks for any help

Link to comment
Share on other sites

I think ginerjm has solved my problem..

 </form>
<form method="post" action="check.php">
  <label for="height">*Height:</label>
<input type="text" name="height[]" id="height" required="required">
  <label for="weight">*Weight:</label>
<input type="text" name="weight[]" id="weight" required="required">
	
  <input type="submit" value="Submit!">
</form>

When I dump the data via

print_r($_POST,true);

I get both values out of the variable, 

 

But yes, I think this is probably exactly the problem.  So should I send the variables to the original page, via some hidden type?  How can I create and keep the array?

Link to comment
Share on other sites

The use of the [] naming style for input elements is to produce an array in $_POST to handle multiple inputs of the same "data". In your case your form is only collecting 1 piece of data for height and 1 for weight. You don't need the array syntax here.

 

Maybe you need to think about your design. If you want multiple pairs of inputs you need to design your form for that and then change your php code to get those arrays. Be careful since there is no connection between the height and weight items meaning that a malicious user could enter a height in the first array element and a corresponding weight into the second weight element, thus your arrays would be out of sync.

 

Do you really need to collect multiple pairs at one sitting? You could also use a $_SESSION var to store your inputs but I don't know what you are really trying to do here, so I'll stop.

Link to comment
Share on other sites

ginerjm, thanks for responding.

 

I know that the code isn't checking for validation, nor is it looking for things like safety, xss attacks etc.  Right now, I'm working on understanding on how to work with arrays and general basics in php/html. 

<?php
/**
 * This is the file, untitled.php
 **/
echo '
 </form>
<form method="post" action="untitled.php">
<p></p>	<label for="height">height:</label>
	<input type="text" name="height[]" id="height" required="required">
<p></p>	<label for="weight">weight:</label>
	<input type="text" name="weight[]" id="weight" required="required">
	
	<p></p><input type="submit" value="Submit!">
</form>
';

// check to see what was sent in post
print_r($_POST, true);
echo '<br>';

// height and weight sent, now put the height and weight each into an array
 $h = $_POST['height'];
 $w = $_POST['weight'];
 
// check the values in each array h and w
 print_r($h);
 echo '<br>';
 print_r($w);
 

// store h and w into an array of arrays, maybe they will increment this way
$hw = array('height' => $h,
	    'weight' => $w );
// check to see what is in hw
print_r($hw);
			   
 ?>

So trying to put the data from the arrays into another array still doesn't do what I want it to do. 

 

It is all in the same file, so I could make sure that the data wasn't being sent from one file to another and out of the variable scope.

 

I suppose, what I am fundamentally trying and failing at understanding is how to take the form data and put it (correctly) into an arrray. 

 

* edit -added clarity

When I wanted to add the values into an array, I don't know why when I hit submit again, it doesn't add those values to the arrays, instead, it simply adds the value to the index = 0 position.  I've been rereading my book on php, but it doesn't say much on taking data from a form to an array.

 

Thanks again,

Edited by fema3
Link to comment
Share on other sites

What you are not getting is that this script is doing things kinda backwards. You begin by echoing a form out. Then you continue by looking at some potential input. That's not how it works. There is no input on the first run of this script but your script is going to try and do something anyway.

 

What about arrays are you trying to learn? PHP arrays? Or html arrays?

 

 

You need to write your scripts like this:

 

PHP code and no html

//*******

HTML code and no php

exit

 

Use the php code to check what your current status is. Do you in fact have some input to process yet? If so then do your logical setups to prepare your output form and then do that output and exit. That's it. If you do have input, process the input and figure out what you want to do with it and then produce the results for the user. Maybe you send back the same form, maybe you send something else. Whatever you do DON'T DO THEM ALL AT ONCE. What you currently have is confusing to me and to you I am sure.

 

Personally I use a single function to generate my output html page. The whole document. Inside that html are several/many php vars that contain the data that the early part of the script generated that were passed to this function. My script is very neat looking with all the php logic at the top and all the html at the bottom. Yes - if the logic has to build an html table then the table elements will be wrapped around the php code but no other html code will be in the php section. Same with a select element.

 

Question - when you do the print_r of the $h and $w does the output suggest an array variable was created? If so your following logic s/b giving you errors. Do you have error properly engaged?

Link to comment
Share on other sites

OK.

 

I thought it wouldn't matter where or how the data came from.  Initially, I built my form by a function, but I've been trying to remove anything that might causing the problem.  Until, I was left with this simple script, and I still don't really understand.  I've always done programming in C++, so there is a lot of stuff I really don't understand about php, it seems really confusing to me. 

 

So really, what I was thinking, was to take in the heights and weights, as the submit button was pressed.  Storing those into arrays, then I could later write some code further down the page that would show what the height or weight of a particular user was (say print out the data in the array at index[y]).  But so far, just trying to understand how to put data from forms into an array has been pretty challenging.

 

 

thumb_5075094Screenshot_from_2017-02-19_

Link to comment
Share on other sites

IMHO php isn't confusing. The learning process for web development may be the confusion. One has to remember that client-server computing is non-conversational. That means you have to be prepared to start from scratch every time your server-side script is triggered by the client-side user. In this case your original idea of saving things in a PHP variable won't work since every time your script is run it begins from step one again. This kind of thing is definitely not new with PHP nor with computing applications. Heck - it was my biggest learning curve when I first learned CICS on IBM's big iron.

 

You stated that you are new at coding. Might I suggest you step back and read a book and get a feel for what you are embarking upon? Then start with the simple scripts that will teach/familiarize you with writing code, understanding code, knowing what it is like to make mistake after mistake until you get it right and scream "Aha!!" at your minor successes. THEN try some new concepts like html arrays when you get used to how the client and the server connect to each other. You wouldn't start taking apart your carburetor without knowing how it works would you? Bend the wrong piece just a little and you'll never get it running smooth again!

Link to comment
Share on other sites

to summarize some of the information that has already been mentioned in this thread -

 

what you seem to be missing, in trying to add newly submitted values into an array with previously submitted values, is that web servers are stateless. each request made to the web server is completely separate from every other request.

 

to make data persist between requests, you must store it somewhere on the server (session variables, database) or you must pass it through the request (as hidden form field data or in cookies.)

 

also, by definition, all values that are part of a http request are strings, regardless of what they represent. it's up to your application code to treat them as what they actually represent.

Edited by mac_gyver
Link to comment
Share on other sites

Thanks for the replies,

 

I'm not new at coding per se, as I said, I have wrote apps in both C and C++. Mostly very basic, simple task things, mostly procedural.  I'm absolutely new at programming in PHP and html.  In fact one of the reasons I am trying to learn PHP is that I created a small c program on an arduino, and at some point I want to be able to put that on the web, and use php to access it and analyze or view  the data. The analogy of a taking a carb apart probably isn't a good analogy for me, as I did that when I was hs to my small dirtbike that I rode around.  Necessity is the mother of all invention I suppose. It never dawned on me that I shouldn't do it for fear of breaking it.

 

I have a book I am trying to follow (PHP and MYSQL by Ullman) and another one by Murach.  They take you through very specific examples, I suppose my first thought was why can't I just write some of these myself.  A lot of things were similar, but I was stumped as to why it was not doing anything I intended it to do, even though all my code appeared correct (to me anyway). 

 

You and mac_gyver are correct that I think what I am missing is that php isn't saving my variables.  In trying to do things incrementally.  It never dawned on me that the program not only begins, but also ends when the user hits the submit button. I looked at another submit as a continuation of the previous.  I had read about "hidden form field" data, but I only glanced at it, it didn't seem like something that was necessary at the time.  At least now, I can at least make a few educated guesses as to what's going on.  Neither of the books I have really address this, though they all use the hidden fields.  Looks like I have more searching and reading to do. 

Link to comment
Share on other sites

I don't think hidden fields are your answer here.

 

As I suggested - re-think your algorithm. Reconsider why you want an array and not a db. If each entry of h/w represent a "record" of some data, save it as such in your db and when you need the sum of the input for that key value, retrieve all the records for that key with a query and build an output display. Maybe consider two scripts - one for collecting multiple h/v pairs for a specific key value and another for outputting formatted data for a specific key value (or more!).

 

What I've just described s/b an easy "first app" for you. Simple form input, retrieval and storage script. And a simple get key, retrieve data and output results (html table?) script.

 

Remember that your scripts have to "recognize" what to do when they execute. The first will have to distinguish between the "first" run where it merely needs to output the form, and then the "second" run where it retrieves the post data and validates it and does the db update. Same for the second script where it sends a query form asking for a key value on the first execution and a similar retrieve and query and output process on the second run. Once you have done one of these cleanly you will surely begin to see how this all works. I do this by checking for the existence of an expected 'submit' type input tag having a value attribute that I put on my form. If I don't see a submit in my post array that is how I know that it is my first time thru. If I do see a submit button I check the value of it to see which of multiple possible submit buttons I may have placed in my form that was clicked and write code to process each button I expect to see. (Such as a 'Return' button to send the user back to a possible menu screen that got me here in the first place.) If I get a submit value that I don't expect, I assume someone is playing with me and I simply echo out an "invalid" message and exit, killing any attempt to break my appl. Remember that you ALWAYS need to validate your user inputs to ensure that they are what you expect.

 

A very important thing you should learn about is using prepared queries to do your db interactions. This will help ensure that your user inputs are safe when you place them into a query string. IMHO - the PDO interface is the way to go rather than mysqlI. Do Not Use the OLD MySQL interface as you'll see it is clearly marked deprecated in the manual and is no longer even available in the most recent versions of PHP.

Edited by ginerjm
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.