Not able to retrieve POST value after form POST --> PHP - php

i have a form with an input box which will double when clicking on add button , something like below
So it will keep on adding UTM ID, and when when i submit the form , the data should be fetched and printed using PHP , but Form gets posted but data is not passed .
So below is my code
<form method="POST" action="" class="basic-repeater" >
<select class="js-example-basic-single">
<option>Select Instance </option>
</select>
<div data-repeater-list="group-a">
div data-repeater-item>
<div class="row">
<div class="col-md-2 col-sm-12 form-group">
<label for="name">UTM ID</label>
<input type="text" class="form-control" name="name[]" id="name" placeholder="UTM Id">
<button type="submit" name="SaveModules" class="btn btn-primary" >Update</button>
</form>
<?php
if (isset($_POST['SaveModules'])){
$UTMID = $_POST['name']; // value not getting retrieved
echo "<script>console.log('Debug Objects: ".$UTMID."' );</script>";
}
?>
So Can anyone help me to figure out the issue

The code don't work because name input (name="name[]") is multiple so in php will be an array.
if you do like that you will see all work because will take the first value of array:
echo "<script>console.log('Debug Objects: ".$UTMID[0]."' );</script>";
Instead if you want multiple ids use a foreach like:
if (isset($_POST['SaveModules'])) {
$UTMID = $_POST['name']; // value not getting retrieved
foreach($UTMID as $id){
echo "<script>console.log('Debug Objects: " . $id . "' );</script>";
}
}
Another "tips" is to don't mixup like that php/js, if you need return in js use AJAX instead, or if you need to debug it use simple echo

I checked this code in local with multiple names and i got the correct array
<form method="POST" action="" class="basic-repeater" >
<div class="col-md-2 col-sm-12 form-group">
<label for="name">UTM ID</label>
<input type="text" class="form-control" name="name[]" id="name" placeholder="UTM Id">
<input type="text" class="form-control" name="name[]" id="name1" placeholder="UTM Id">
<input type="text" class="form-control" name="name[]" id="name2" placeholder="UTM Id">
<input type="text" class="form-control" name="name[]" id="name3" placeholder="UTM Id">
<button type="submit" name="SaveModules" class="btn btn-primary" >Update</button>
</div>
</form>
<?php
if (isset($_POST['SaveModules'])){
$UTMID = $_POST['name'];
print_r($_POST);
//echo "<script>console.log('Debug Objects: ".$UTMID."' );</script>";
}
?>
and i got the result in post
[name] => Array ( [0] => 12 [1] => 34 [2] => 56 [3] => 78 ) [SaveModules] => )
and if you need the array in javascript then you need to use json_encode because you can not print php array direct in console.log
echo "<script>console.log('Debug Objects: ".json_encode($UTMID)."' );</script>";
Debug Objects: ["rret","dfgdfg","dfgfg","ghvnv"] index.php:12:9

name=name[] will be an array.
$name[number] //to retrieve array values
Multiple input with same name.
You can set name=value[]
Then you can retrieve the value with.
val[0] //leads to the first value
This is sample php got implode array value
<?php
if(isset($_POST['SaveModules'])){
$VAL= $_POST['name'];
$UTMID = implode(', ',$VAL);
echo $UTMID; //output = Value1, Value2, Value3
// echo "<script>console.log('Debug Objects: ".$UTMID."' );</script>";
}

Try changing your name="name[]" to something like name="UTM" as you are looking for name[] and also requesting name
As for the multiple posts, you could add in your script that makes a new input box and add n after UTM, this would be good as you also know which box they are filling in.
Here:
<form method="POST" action="" class="basic-repeater" >
<div class="col-md-2 col-sm-12 form-group">
<label for="name">UTM ID</label>
<input type="text" class="form-control" name="UTM1" id="name" placeholder="UTM Id">
<button type="submit" name="SaveModules" class="btn btn-primary" >Update</button>
</form>
<?php
if (isset($_POST['SaveModules'])){
$UTMID = $_POST['UTM1']; // value not getting retrieved
echo "<script>console.log('Debug Objects: ".$UTMID."' );</script>";
}
?>

Related

How to insert data from a form into a table in php without using databsaes?

I need to create a table of 17 rows where each row contains information such as row number, name, surname, email and birthday. The data is provided by this form:
<form action="index.php" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="emailbirthday" placeholder="emailbirthday" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
</form>
After clicking submit the data should be displayed in the nth row of the table(row number one if it is the first "pack" of data submitted, number two if its the second and so on). This problem could easely be solved using databases but i cannot use them(by professors order).
I tried to create an array than push values into it like this:
$array_name = array();
$name = $_POST["name"];
array_push($array_name, $name);
This approach doesn't work(the index of the array stays 0 alla of the time so it keeps replacing the first value again and again) and manually incrementing the index counter of the array doesn't work either.
Normally one should use a database approach but your professor explicitly forbids it.
There are many other ways to do it. (store as TEXT/JSON/CSV file or localstorage / cookies), etc. For me I would use session to do the job
declare a session variable which is an array
if user submits the form, store the POST data into another array (subarray) containing name, surname, birthday, email
add the subarray into the main session variable array
print it out at the end as a table
So the PHP will be:
<?php
session_start();
?>
<form action="#" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="email" placeholder="email" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
</form>
<?php
if (!isset($_SESSION["arr"])){
$_SESSION["arr"]=array();
}
if ($_POST) {
$subarray=array(
"name"=>$_POST["name"],
"surname"=>$_POST["surname"],
"birthday"=>$_POST["birthday"],
"email"=>$_POST["email"]
);
$_SESSION["arr"][]=$subarray;
}
echo "<table border=1><tr><td>Name<td>Surname<td>Email<td>Birthday";
foreach($_SESSION["arr"] as $suba){
echo "<tr><td>" . $suba["name"] ;
echo "<td>" . $suba["surname"] ;
echo "<td>" . $suba["email"] ;
echo "<td>" . $suba["birthday"] ;
}
echo "</table>";
?>
However, if you need the data to be persistent (even after the user closes the browser), then you need to store the data say in file format or cookies, etc.
If you need to save data persistent and using file to save data is acceptable, i'd use something like that:
<?php
$file = 'path/to/file.txt';
$data = json_decode(file_get_contents($file), true);
if ($_POST) {
$data[] = [
"name" => $_POST['name'],
"surname" => $_POST['surname'],
"emailbirthday" => $_POST['emailbirthday'],
"birthday" => $_POST['birthday']
];
}
file_put_contents($file, json_encode($data));
?>
<form action="index.php" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="emailbirthday" placeholder="emailbirthday" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
</form>
<table>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Emailbirthday</th>
<th>Birthday</th>
</tr>
<?php
foreach ($data as $row) {
print '<tr>
<td>'.$row['name'].'</td>
<td>'.$row['surname'].'</td>
<td>'.$row['emailbirthday'].'</td>
<td>'.$row['birthday'].'</td>
</tr>';
}
?>
</table>
You can use the post values of hidden fields:
<form action="" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="emailbirthday" placeholder="emailbirthday" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
<?php
if($_POST["names"] == "")
{
$value = $_POST["name"];
}
else
{
$value = $_POST["names"]."-".$_POST["name"];
}
?>
<input type="text" name="names" style='display:none;' value="<?php echo $value ?>">
</form>

I am trying to figure out how to pass a php variable that includes html code to another page using a form

I have query results returned in an array on page1 and I want two of those results to pass and populate a form on page2. i have that part working except that one of the variables is a paypal button which includes html so it ends up displaying the button on page1 and does not let user click to page2. Besides displaying the button it displays " />. I need to know how, if possible, to pass the button details to become the "submit" button on page2. Thanks.
THIS IS PAGE1 CODE:
$results=mysqli_query($connection, $sql);
if (mysqli_num_rows($results) < 1) {
echo "<br>We are working on this trip's details.<br><br><h3
style='color:#C8FE2E'>Check back soon!</h3>";
} else {
$tripID = 1; //temp var
$payButton = 2; //temp var
while($row=mysqli_fetch_array($results)) {
echo"Trip ID: " .$row[1].
"<br>Date: " .$row[3].
"<br>Departs From: " .$row[4].
"<br>Departure Time: " .$row[5].
"<br>Arrives at Casino: " .$row[6].
"<br>Leaves at Casino: " .$row[7].
"<br>Arrives at Drop Off: " .$row[8].
"<br>Drop Off Location: " .$row[9].
"<br>Price: $" .$row[10].
"<br><br>Trip Details: " .$row[11]
;
$tripID = $row[1];
$payButton = $row[14]; //should not display on this page
echo "";
}
}
if(mysqli_num_rows($results) > 0) {
?>
<br><br>
<form action="reserve-form.php" method="POST">
<input type="hidden" name="tripID" value="<?php echo $tripID; ?>"/>
<input type="hidden" name="payButton" value="<?php echo $payButton;?>"/>
<button class='reg-btn' type="submit" name="clicked" style='border:none' >Register Now</button>
</form>
<?php
}else{
echo"";
}
mysqli_close($connection);
?>
AND THIS IS PAGE2 (where the button SHOULD display):
Reserve your Seat
<div class="form-group">
<label>Trip ID#</label>
<input class="form-control" type="text" name="tripID" value="<?php echo
$_POST['tripID']; ?>" readonly>
</div>
<div class="form-group">
<label>First Name</label>
<input class="form-control" type="text" name="firstName" required >
</div>
<div class="form-group">
<label>Last Name</label>
<input class="form-control" type="text" name="lastName" required>
</div>
<div class="form-group">
<label>Phone Number</label>
<input class="form-control" type="text" name="phone" required>
</div>
<div class="form-group">
<label>Email Address</label>
<input class="form-control" type="email" name="email" required>
</div>
<center><input class="btn btn-success" id="submit_btn" type="submit" value="Submit" name="submit">
<img src="images/Spinner-gif.gif" class="ld_img" style="display:none;"/>
</center>
</form>

MVC Sending Values to Form

I have been making a site to learn about MVC, I am trying to add a function to the update option. At the moment I have two buttons on each row (one to delete and one to update), when the update button is pressed a form to update the row appears on the right of the screen.
I am trying to pre-populate the form when the user presses the update the button but I dont know how to do that within an MVC. Should I create a function that does this or should I have some PHP at the top of the form to pre-populate?
Any help or advice will be great
Update Form to be pre-populated
<h2>Update Item!</h2>
<h4>Fill in the form to update an entry.</h4>
<form action="index.php" method="post">
<fieldset>
<input id='action' type='hidden' name='action' value='updateItem' />
<p>
<label for="fTitle">Title</label> <input type="text"
id="fTitle" name="fTitle" placeholder="title"
maxlength="25" required />
</p>
<p>
<label for="fPrice">Price</label> <input type="text"
id="fPrice" name="fPrice" placeholder="price"
maxlength="25" required />
</p>
<p>
<label for="fDescription">Description</label> <input type="text"
id="fDescription" name="fDescription" placeholder="description"
maxlength="500" required />
</p>
<p>
<div class="form-group">
<div class="controls">
<button type="submit" class="btn btn-success">Update</button>
</div>
</div>
</p>
</fieldset>
</form>
Update button in the View receiving the row ID for the button
$update = file_get_contents( "templates/updateButton.php");
$HTMLItemList = "";
foreach ( $this->model->itemList as $row )
$HTMLItemList .= "<li><strong>" . $row ["title"] . ": </strong>" . "€" .$row ["price"] . "<blockquote>" .
$row ["description"] . " " . str_replace("value2replace", $row['id'], $delete) .
str_replace("value2replace", $row['id'], $update) . "</blockquote></li>";
Update Button
<form action="index.php" method="post">
<fieldset>
<input id='action' type='hidden' name='action' value='updateStart' />
<div class="form-group">
<div class="controls">
<input type="hidden" id="fId" name="fId" value="value2replace">
<input type="submit" class="btn btn-success" value="Update" />
</div>
</div>
</fieldset>
</form>
This is a question I've struggled with before, and still haven't found a satisfactory solution for. How I've seen it done is that your Controller passes down the data to the view that contains your form, and then you use PHP echo statements to fill in the data automatically.
I've also seen a counter approach where each form is an Object, so for instance:
class ItemForm{
public function render(Item $item = null){
//create form and fill in data if $item is not null
}
Basically the render function will decide whether to fill in information for you or not, depending on it Item is null or not.
Personally, I like the class version better, just because then you can use it in various places if need be.

Custom form posting "Array" rather than user input values

We are using the Aheadworks Helpdesk Module and are trying to create a second form to capture specific information and use the form to create a ticket where all of the form content gets posted to the "content" section of Helpdesk.
The problem is, if I use the name="content", what gets posted into the "content" section is simply "Array"
The form code is quite simple:
<form id="helpdesk-ticket-form" action="../helpdeskultimate/customer/new/" method="post" enctype="multipart/form-data"><input name="title" value="WHOLESALE SETUP REQUEST" type="hidden">
<div><label for="title_field">Name<span class="required">*</span></label><br> <input id="title" class="input-text required-entry" style="width: 250px;" name="" value="" type="text"></div>
<div> </div>
<div><label for="title_field">Company Name<span class="required">*</span></label> <br><input id="content_field" class="input-text " title="Company" name="content" value="" type="text"></div>
<input name="department_id" value="2" type="hidden">
<div> </div>
<div><label for="content_field">Message<span class="required">*</span></label><br> <textarea id="content_field" class="required-entry" style="width: 450px;" name="content" rows="10" cols="53"></textarea></div>
<div> </div>
<div> </div>
<div><label for="filename">Attach Reseller Permit (2Mb limit)</label><br> <input id="filename" class="input-file" style="width: 450px;" name="filename" type="file"></div>
<div class="button-set"> </div>
<div class="button-set"><span><span><br></span></span></div>
<div class="button-set"><button class="button right form-button" type="submit"><span> <span>Submit ticket</span></span> </button></div>
</form>
I have tried using name="content[]" but it also returned "Array"
The module looks to be using this post method:
public function newAction()
{
if (!$this->_getCustomerSession()->getCustomerId()) {
$this->_getCustomerSession()->authenticate($this);
return;
}
$session = Mage::getSingleton('core/session');
$customer = $this->_getCustomerSession()->getCustomer();
$Proto = Mage::getModel('helpdeskultimate/proto');
$postData = $this->getRequest()->getPost();
if (isset($postData['department_id'])) {
$Proto->setDepartmentId($postData['department_id']);
}
try {
$Proto
->setSubject(#$postData['title'])
->setContent(#$postData['content'])
->setPriority(#$postData['priority'])
->setStoreId(Mage::app()->getStore()->getId())
->setFrom(Mage::getSingleton('customer/customer')->getId())
->setSource('web');
The insert into the message field seems to come from here:
/* Insert */
try {
$message->setContent(trim($data['content']));
$validateResult = $message->validate();
The full controller file can be downloaded from http://www.gingabox.com/CustomerController.zip
I am not sure how to actually use a foreach statement with the #$postData['content'], or if there is a better solution.
I would happily ask AheadWorks, but have been told by them that they are not accepting customization inquiries at this time (too busy)...
Any help would be greatly appreciated!
The word "Array" is what you get when you convert a PHP array into a string; since array values can contain anything, PHP doesn't bother trying to figure out how to convert an array and just returns the string "Array". This is exactly what happens in the line:
// The trim() function casts $data as a string => string(5) "Array"
$message->setContent(trim($data['content']));
There are functions that do return a string representation of array contents, such as print_r(). This will spit out the array in a multiline string, so incorporating that in your code would be:
$message->setContent(print_r($data['content'], TRUE));
If you wanted the contents of the array as a single-line string you should probably use a foreach() statement like you mentioned in your question. Here's a quick example:
$contentString = 'Second Form values:' . PHP_EOL;
foreach($data['content'] as $key => $value) {
$contentString .= PHP_EOL . ' ' . $key . ': ' . $value;
}
Then you would be able to use $contentString as the message instead of accessing the $data array value directly. I don't know what the validate() method is doing in your example, but it is definitely a good idea to ensure that you are properly escaping the values within this second form before you use them as the body of an email.
If you can change the form definition in HTML then maybe you will be able to receive an array as content, please have a look at the following example:
<form id="helpdesk-ticket-form" action="tescik.php" method="post" enctype="multipart/form-data"><input name="title" value="WHOLESALE SETUP REQUEST" type="hidden">
<div><label for="title_field">Name<span class="required">*</span></label><br> <input id="title" class="input-text required-entry" style="width: 250px;" name="content[name]" value="" type="text"></div>
<div> </div>
<div><label for="title_field">Company Name<span class="required">*</span></label> <br><input id="content_field" class="input-text " title="Company" name="content[company]" value="" type="text"></div>
<input name="department_id" value="2" type="hidden">
<div> </div>
<div><label for="content_field">Message<span class="required">*</span></label><br> <textarea id="content_field" class="required-entry" style="width: 450px;" name="content[message]" rows="10" cols="53"></textarea></div>
<div> </div>
<div> </div>
<div><label for="filename">Attach Reseller Permit (2Mb limit)</label><br> <input id="filename" class="input-file" style="width: 450px;" name="filename" type="file"></div>
<div class="button-set"> </div>
<div class="button-set"><span><span><br></span></span></div>
<div class="button-set"><button class="button right form-button" type="submit"><span> <span>Submit ticket</span></span> </button></div>
</form>
Please note the changed form names like content[message], content[company] etc. This should resolve to an Array of values.

Inserting Multiple rows in Mysql table with PHP

I am in a fix here. I have code that does not insert multiple data into mysql table with one form. Here's my code-
<?php
if (isset($_POST['submitted'])) {
include('config.php');
foreach($_POST['name'] as $row=>$nam) {
$name=$nam;
$class=$_POST['class'][$row];
echo "<br/>" . $name . "<br/>" . $class;
$sql="INSERT INTO multiple (name, class) VALUES ('$name','$class')";
}
if (!mysql_query($sql)) die('Error: ' . mysql_error());
echo "1 record added";
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label>Name1:
<input id="name" name="name[]" type="text">
<input type="hidden" name="submitted" value="true" />
</label>
<label> Class1:
<input id="class" name="class[]" type="text">
</label>
<label>Name2:
<input id="name" name="name[]" type="text">
</label>
<label>Class2:
<input id="class" name="class[]" type="text">
</label>
<label>Name3:
<input id="name" name="name[]" type="text">
</label>
<label>Class3:
<input id="class" name="class[]" type="text">
</label>
<label>Name4:
<input id="name" name="name[]" type="text">
</label>
<label>Class4:
<input id="class" name="class[]" type="text">
</label>
<label>Name5:
<input id="name" name="name[]" type="text">
</label>
<label>Class5:
<input id="class" name="class[]" type="text">
</label>
<input value="Add" type="submit">
</form>
When I press the submit button nothing inserts in the mysql table. Only empty fields are created. If I insert 5 text field I get 5 empty fields in sql table.
Imroz, your use of [] as part of the names of your input elements (not id's) example name="class[]" when the form is posted it builds an array. The post object PHP would recognize would be $_POST['class']
But that being an array means you have to handle it slightly different before inserting it into your database as you can't just (well maybe you can) drop an array into the DB
if you did
for($x=0;$x < count($_POST['class']); $x++)
{
echo $_POST['class'][$x].'<br>';
}
you would be able to see all your posted inputs from the inputs with the name class[]
of course this is a core example of what you need to do overall, but I am just trying to express whats going on with your posted data.
i think your inserting query is problem.....try like this
$query = mysql_query("INSERT INTO category VALUES('','$name','$class','')") or die(mysql_error());
You have the } in the wrong place.
The } right after the $sql= should be moved after the echo "1 record added";
I reformatting your code to use proper indenting and the error was obvious.

Categories