Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve post array values

Tags:

arrays

jquery

php

I have a form that sends all the data with jQuery .serialize() In the form are four arrays qty[], etc it send the form data to a sendMail page and I want to get the posted data back out of the arrays.

I have tried:

$qty = $_POST['qty[]'];
foreach($qty as $value)
{
  $qtyOut = $value . "<br>";
}

And tried this:

for($q=0;$q<=$qty;$q++)
{
 $qtyOut = $q . "<br>";
}

Is this the correct approach?

like image 883
StudentRik Avatar asked Feb 13 '14 09:02

StudentRik


People also ask

What is the use of $_ POST array in PHP?

PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post".

Is $_ POST an array?

The PHP built-in variable $_POST is also an array and it holds the data that we provide along with the post method.

How do you post data in an array?

To post an array from an HTML form to PHP, we simply append a pair of square brackets to the end of the name attribute of the input field. For example: <form method="post"> <input name="favorites[]" type="text"/>

Why $_ POST is empty?

In my case, when posting from HTTP to HTTPS, the $_POST comes empty. The problem was, that the form had an action like this //example.com When I fixed the URL to https://example.com , the problem disappeared. I think is something related on how the server is setup. I am having the same issues using GoDaddy as a host.


2 Answers

You have [] within your $_POST variable - these aren't required. You should use:

$qty = $_POST['qty'];

Your code would then be:

$qty = $_POST['qty'];

foreach($qty as $value) {

   $qtyOut = $value . "<br>";

}
like image 85
ajtrichards Avatar answered Oct 19 '22 13:10

ajtrichards


php automatically detects $_POST and $_GET-arrays so you can juse:

<form method="post">
    <input value="user1"  name="qty[]" type="checkbox">
    <input value="user2"  name="qty[]" type="checkbox">
    <input type="submit">
</form>

<?php
$qty = $_POST['qty'];

and $qty will by a php-Array. Now you can access it by:

if (is_array($qty))
{
  for ($i=0;$i<size($qty);$i++)
  {
    print ($qty[$i]);
  }
}
?>

if you are not sure about the format of the received data structure you can use:

print_r($_POST['qty']);

or even

print_r($_POST);

to see how it is stored.

like image 33
Thomas Avatar answered Oct 19 '22 12:10

Thomas