Asked  7 Months ago    Answers:  5   Viewed   32 times

I have a form on my page with a bunch of inputs and some hidden fields, I've been asked to pass this data through a "post array" only im unsure on how to do this,

Heres a snippet of what im doing at the moment

<form enctype="multipart/form-data" action="process.php" method="POST"> 
...
more inputs
...

<!-- Hidden data -->
<input type="hidden" name="TimeToRenderHoursInput" value="<?php echo $RenderHours; ?>" />
<input type="hidden" name="TimeToRenderDaysInput" value="<?php echo $RenderDays; ?>" />
<input type="hidden" name="TimeToRenderYearsInput" value="<?php echo $RenderYears; ?>" />
<input type="hidden" name="ContentMinutesInput" value="<?php echo $ContentMinutes; ?>" />
<input type="hidden" name="ContentMinutesSelector" value="<?php echo $ContentMinutesSelector; ?>" />
<input type="hidden" name="PriorityInput" value="<?php echo $Priority; ?>" />
<input type="hidden" name="AvgFrameRenderTimeInput" value="<?php echo $AverageFrameRenderTime; ?>" />
<input type="hidden" name="AvgFrameRenderTimeSelector" value="<?php echo $AverageFrameRenderSelector; ?>" />
<input type="hidden" name="CoresInTestInput" value="<?php echo $CoresInTest; ?>" />
<input type="hidden" name="EstPriceInput" value="<?php echo $EstPrice; ?>" />
<!-- End hidden -->

<input type="image" src="http://www.venndigital.co.uk/testsite/renderbutton/_includes/images/button/submit.jpg" alt="Submit" value="Submit" style="border:0!important;" />

In my process.php im then calling the data as such...

$first_name = $_POST['first_name']; 
$company_name = $_POST['company_name']; 
$email_from = $_POST['email']; 
$address = $_POST['address']; 
$postcode = $_POST['postcode']; 
$RenderHours = $_POST['TimeToRenderHoursInput'];
$RenderDays = $_POST['TimeToRenderDaysInput'];
$RenderYears = $_POST['TimeToRenderYearsInput'];
$ContentMinutes = $_POST['ContentMinutesInput'];
$ContentMinutesSelector = $_POST['ContentMinutesSelector'];
$Priority = $_POST['PriorityInput'];
$AverageFrameRenderTime = $_POST['AvgFrameRenderTimeInput'];
$AverageFrameRenderSelector = $_POST['AvgFrameRenderTimeSelector'];
$CoresInTest = $_POST['CoresInTestInput'];
$EstPrice = $_POST['EstPriceInput'];

Is there a way to post it as an array? Is my method bad practice in anyway?

 Answers

81

Give each input a name in array format:

<input type="hidden" name="data[EstPriceInput]" value="" />

Then the in PHP $_POST['data']; will be an array:

  print_r($_POST);         // print out the whole post
  print_r($_POST['data']); // print out only the data array
Wednesday, March 31, 2021
 
SheppardDigital
answered 7 Months ago
92

@Emily With respect to your updated questions, its easy to achieve. Pass the array itself to ajax post like this

$.ajax({
     url: 'reward.php',
     data: {'requestids' : response.data},
    type: "POST",
    success: function(response){
      if(response==1){
         alert("Reward Applied!");
             }
      else{
         alert("Reward Failed!");
             }
        }
   });
  }
}

Then in your PHP loop through requestids array and generate mysql query to insert all records at once like this

$sql= "INSERT INTO requestids (requestid) VALUES "; 
foreach($_POST['requestids'] as $requestId){
       $sql.="($requestId)";
}

I am sure you can easily convert this simple query into a PDO statement

Wednesday, March 31, 2021
 
DiglettPotato
answered 7 Months ago
52

To pass it in as an array of values, add square brackets to the name attribute of your select element..

<select name="names[]" multiple="multiple"> 

Then you can iterate over the values in php.

foreach ( $_POST['names'] as $selectedOption )
Saturday, May 29, 2021
 
EastSw
answered 5 Months ago
66

Instead of checking !isset(), use empty(). If the form posts an empty string, it will still show up in the $_POST as an empty string, and isset() would return TRUE.

I've replaced your incremental for loop with a foreach loop, which is almost always used in PHP for iterating an array.

$out_data = array();
foreach ($form_data as $key) {
    if(empty($_POST[$key])) {
        $out_data[$key] = "NO_DATA";
    }
    else {
        $out_data[$key] = $_POST[$key];
    }
}
Saturday, May 29, 2021
 
axiomer
answered 5 Months ago
30

Note: The main cause for your code to output array() is the fact that you're redirecting the client before the asynchronous (AJAX) request has been sent/processed
Basically move window.location = "AddtoDatabase.php"; to the success callback, as mentioned further down.

First problem: Instead of using an array, you should use an object literal (~= assoc array in php).

To do so, change this bit:

var dataArray = new Array(7);//<== NEVER do this again, btw
dataArray[0]= "routeID:" + routeID;
dataArray[1]= "custID:" + custID;
dataArray[2]= "stopnumber:" + stopnumber;
dataArray[3]= "customer:" + customer;
dataArray[4]= "latitude:" + lat;
dataArray[5]= "longitude:" + lng; 
dataArray[6]= "timestamp:" + timeStamp; 

And write this, instead:

var dataObject = { routeID: routeID,
                   custID:  custID,
                   stopnumber: stopnumber
                   customer: customer,
                   latitude: lat,
                   longitute: lng,
                   timestamp: timeStamp};

There's nothing more too it. To finish off, just send the data like so:

function postData()
{
    $.ajax({ type: "POST",
             url: "AddtoDatabase.php",
             data: dataObject,//no need to call JSON.stringify etc... jQ does this for you
             cache: false,
             success: function(resopnse)
             {//check response: it's always good to check server output when developing...
                 console.log(response);
                 alert('You will redirect in 10 seconds');
                 setTimeout(function()
                 {//just added timeout to give you some time to check console
                    window.location = 'AddtoDatabase.php';
                 },10000);
             }
    });

Secondly, your postData function redirects the client before the AJAX request has been sent! After the call to $.ajax, you have a window.location = "AddtoDatabase.php"; statement in your code. If you want the client to be redirected after the ajax call, you will have to move that expression to your success callback function (the one where I log the response) in the second snippet ^^.

When you've changed all this, your $_POST variable should look about right. If not, print out the $_REQUEST object and see what the response of an ajax call is then.

Lastly, please be aware that using an api that supports prepared statements (and thus protects you against most injection attacks), that doesn't mean stringing unchecked POST/GET data into a query is any safer than it used to be...
Bottom line: When you use an API that supports critical safety features such as prepared statements use those features.

Just to be absolutely clear, and complete, here's a slightly reworked version of the PHP code, too:

$routeID = $_POST['routeID'];
$custID = $_POST['custID'];
$stopnumber = $_POST['stopnumber'];
$customer = $_POST['customer'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$timestamp = $_POST['timestamp'];
//you're connecting OO-style, why do you switch to procedural next?
//choose one, don't mix them, that makes for fugly code:
$mysqli = mysqli_connect('fdb5.biz.nf', 'username', 'password', 'database');//procedural
//or, more in tune with the times:
$mysqli= new mysqli("fdb5.biz.nf","username","password","database");//OO

mysqli_select_db($mysqli,"database");
//or
$mysqli->select_db('database');

Check the docs to see the procedural counterpart of all methods I'll be using from here on end, if you want. I prefer the OOP-API

//making a prepared statement:
$query = 'INSERT INTO Locations 
          (routeID, custID, stopnumber, customer, latitude, longitude, timestamp) VALUES 
          (?,?,?,?,?,?,?)';
if (!($stmt = $mysqli->prepare($query)))
{
    echo $query.' failed to prepare';
    exit();
}
$stmt->bind_param('s', $routeID);
$stmt->bind_param('s',$custID);
//and so on
$stmt->bind_param('d', $latitude);//will probably be a double
$stmt->execute();//query DB

Useful links on prepared statements:

  • mysqli::prepare doc page
  • mysqli_stmt::bind_result doc page is invaluable when it comes to fetching data...
  • quick tutorial 1
  • Q&A-styled tutorial 2
  • Just in case: a PDO tutorial, too
Wednesday, August 4, 2021
 
lena
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :