Hello i try to send an array multiple times from html form and later access this value's but im recieving undefined index. Can you please explain me what am i doing wrong here ?
First i take all values of checked checkboxe's
<label>
<input type="checkbox" class="ck" name="event[]" id="event" value="<?php echo $row['name'];?>"><span>Wybierz</span>
</label>
Later on i process it and return values into hidden input fields
$event = $_POST['event'];
foreach ($event as $key) {
echo "<input type='text' class='form-control' name='event2[]' value='" . $key . "' />";
}
And lastly i want to send this data together with some other input fields data to thankyou.php but im getting undefined index on my event2
if (isset($_POST['submit2'])) {
if(count($_POST['name']) > 0) {
$event2 = $_POST['event2'];
print_r($event2);
}
exit;
}
Till step 3 everything works perfectly fine .
On each request, only the values that are in the current form are sent to the server. If you want to keep them through multiple requests, either you save them in the session or output them as hidden fields in your form.
change this line:
$event = $_POST['event'];
to this line:
$event = $_POST['event[]'];
Let me know if that worked! :)
Related
I dont know how to manage this situation, I'm a noob coder, I have a page that shows you all available lots where you can unload a specific item from that lot.
This is the foreach that prints out:
$lotto, $totalelotto, $data, and ask for qtyvalue to unload from $lotto (input can be also NULL)
foreach ($dataslotto as $data) {
$totalelotto = totlotto($database, $data['lotto']);
$lotto = $data["lotto"];
$data = $data["data"];
echo "<tr>";
echo "<td>".$lotto."</td>";
echo "<input type=\"hidden\" value=\"".$lotto."\" name=\"array[]\" />";
echo "<td>".$totalelotto."</td>";
echo "<input type=\"hidden\" value=\"".$totalelotto."\" name=\"array[]\" />";
echo "<td>".$data."</td>";
echo "<input type=\"hidden\" value=\"".$data."\" name=\"array[]\" />";
echo "<td><input type=\"text\" class=\"form-control\" placeholder=\"Qta.\" required name=\"qtyvalue\"></td>";
echo "</tr>";
}
I dont know how to set name="" of input fields (because the number of fields can change if there are many lots) and I dont know how to send $_POST data as array, and then foreach group of $lotto, $totalelotto, $data, $qtyvalue where is set $qtyvalue do another query.
I put it in no regular code, I know it looks bad but it's just for giving you an idea.
$_POST[''formarray];
foreach ( /* values recieved in each <tr> inside formarray where $_POST['qtyvalue'] is not empty */ ){
#EXECUTE THIS
}
Thanks for help!!
And sorry for my bad coding skills.
$_POST is an Associative/Key Value pair, it's key is whatever is set as the inputs name.
so if you wanted to send the users input username to the backend PHP script
You set the value and it's name
<input type="text" name="username" value="User123">
then to retrieve the user name you can do
print_r($_POST["username"]);
to print the value.
So you ask how do you loop over each one in $_POST, that's pretty simple you can could a foreach loop over the entire $_POST array.
foreach($_POST as $key => $value)
{
//check something has been entered for the current value we are iterating over
if($value != null)
{
print_r($key . " value is : " . $value);
}
}
this would loop over each item in the $_POST array with key being set to whatever the DOM elements name is.
Don't forget the $_POST array is just that an array, you could do
var_dump($_POST);
and see everything that was sent in the POST request.
You can use array names for your inputs. Say you have a row of your table like this:
<tr>
<td><input ... name="lotto[]"></td>
<td><input ... name="totalelotto[]"></td>
<td><input ... name="data[]"></td>
<td><input ... name="qtyvalue[]"></td>
</tr>
Then you will get arrays $_POST['lotto'], $_POST['totalelotto'] and so on, each with the same number of elements, and elements with same index belonging to one row of the table. You could then process those elements like this
foreach ($_POST['lotto'] as $i=>$lotto) {
if ($_POST['qtyvalue'][$i] > 0) {
...
}
}
I have a MySQL database with auto-increment column "line numbers." In the form that is being submitted to the script, there are check boxes. I don't know how many check boxes there are, because each Customer has a different number of services that they're allowed to access. When the check box is clicked, they've used a service and the integer in column Available for that row needs to decrease by one. Sometimes, the user can say that multiple services were used and more than one row needs to be affected.
Where I'm becoming stuck is on two things: how the check boxes are named, and if I name them by the line number, how to access them with PHP.
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='" . $cell['line_item'] . "'>";
}
The above code is how I'm making the check box. Probably the biggest part of the question is how I could better name it so that I can predict what names to look for ($_POST[name]) when the form is submitted (instead of a random number).
The other part I'm getting stuck on is, if I do decide to keep the naming strategy, how to fetch it. What I've thought of is to use a loop to extract the true/false data that's carried, but I don't know how to execute that. Sure, I can write a for or while loop, but I don't know how to extract the name of the object.
Is there any way I could carry extra data to a PHP script, other than the name?
Is there a better way I could name the check box so that I'm not stuck having to figure out a complicated way of finding the data, retrieving the name, etc.
I'm sort of a beginner when it comes to PHP. I know how to get my way around with for loops, while loops, basic commands such as echo... but I'm really lacking
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='checkboxname[]' value ='".$cell['line_item']."'>";
}
It should do a $_POST array with the name checkboxname inside that array, you find the values.
You can find it threating $_POST['checkboxname'] as an array.
Try name it like: "checkbox_" . $cell['line_item'] so you can do something like this:
foreach($_POST as $name => $value)
{
if(substr($name, 9) == "checkbox_"){
//USE the value
}
}
or you could name like this:
echo "<input type='checkbox' name='services[]' value='" . $cell['id'] . "'>";
and get it as an array like this: $services = $_POST["services"];
Alright. Since you wanted to be able to add extra data, I thought I'd start over complicating stuff a lot! But it does the job. Explanation can be found in the codes comments.
First the HTML and Javascript part:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
// First we need to get our form
var myForm = document.getElementById("myForm");
// Next we're adding an event listener to the form submit so we can catch it
// and use a function to do some stuff before sending it over to the php file
myForm.addEventListener("submit", function(event){
// Now we need to temporarely stop the form from submitting
event.preventDefault();
// Next we need to get all our checkboxes
var checkBoxes = document.getElementsByClassName("myCheckbox");
// Now we need some arrays for all the data we're going to send over
// Basicly you make one for each data attribute
var lineNr = [];
var someThing = [];
// Lets loop through all checkboxes
for (var i=0; i<checkBoxes.length; i++) {
// Catch the ones checked
if (checkBoxes[i].checked) {
// Push the data attribute values to the arrays
lineNr.push(checkBoxes[i].dataset.linenr);
someThing.push(checkBoxes[i].dataset.something);
}
}
// Now we to JSON encode these arrays to send them over to PHP
var jsonLineNr = JSON.stringify(lineNr);
var jsonSomeThing = JSON.stringify(someThing);
// Since we cannot directly add these variables to our form submit,
// unless we use Ajax, we need to add them to our form in some
// hidden fields
myForm.innerHTML += "<input type='hidden' name='jsonLineNrs' value='"+ jsonLineNr +"' />";
myForm.innerHTML += "<input type='hidden' name='jsonSomeThings' value='"+ jsonSomeThing +"' />";
// All done, now we submit our form
myForm.submit();
}
</script>
</head>
<body>
<form method="POST" action="your_php_file.php" id="myForm" accept-charset="utf-8">
<input type="checkbox" class="myCheckbox" data-linenr="1" data-something="value1" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="2" data-something="value2" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="3" data-something="value3" />
<br />
<input type="submit" value="Submit" />
</form>
</body>
</form>
Next the PHP part:
<?php
// First we need to decode the JSON strings so we can use them
$jsonLineNrs = json_decode($_POST['jsonLineNrs']);
$jsonSomeThings = json_decode($_POST['jsonSomeThings']);
// Now both of those variables are arrays that contain all the data you wanted
// You can loop each of them to do stuff like
foreach($jsonLineNrs as $jsonLineNr){
echo $jsonLineNr; //Will echo out each line number
}
// Or if you want to loop through both simultaneously so you can
// keep each checked box data values together:
for($i=0; $i<count($jsonLineNrs)-1; $i++) {
echo $jsonLineNrs[$i].' - '.$jsonSomeThings[$i];
}
?>
Now before I finish this answer, one last warning: I didn't sanitize the user input in the Javascript part. It would make this answer even a lot more complicated and way to long. Be sure to do this, as you can NEVER EVER trust user input! Even if it's only checkboxes, POST data can be changed before it's submitted!
I would prefix the names depending on context, for example:
<input type='checkbox' name='service_" . $cell['line_item'] . "'>"
This way, if the checkbox represents a service, you could identify it by the prefix.
I am trying to create a 'submit' input type button that when clicked will call up a switch case action that I've defined in PHP. When the 'submit' button is clicked, I want the form action to essentially create a link and display in the URL form action so that it is called properly by the PHP file.
However when I click on the submit button, the URL does not properly display the desired link and action.
PHP:
$getuserid_result = mysql_query($getuseridsql, $conn);
$userid_array = mysql_fetch_array($getuserid_result);
$userid = $userid_array['uid'];
// Above code works fine and retrieves the current user's ID
// PHP Form code is below
// Variables used for creating the id of the input since the submit button is displayed
// in an HTML table with multiple rows. These variables are working fine.
$time_cell_row = 1;
$time_cell_column = 1;
echo "<form action='enter_time.php?uid='" . $userid . "?action=timesubmit method='get'>";
echo "<td><input name=submit_time type=submit id=submit_time" . $time_cell_row . $time_cell_column . "></input></td>";
echo "</form></tr>";
// PHP Action code
/* This is currently commented out and will eventually be filled with code to handle
the 'timesubmit' action
if (isset($_GET['action'])) {
switch (strtolower($_GET['action'])) {
case 'timesubmit':
}
}
*/
The problem now is when I click on the 'submit' button, the URL displayed enter_time.php?submit_time=Submit" instead of "enter_time.php?uid=3?action=timesubmit
You might want to add in the final apostrophe after timesubmit
echo "<form action='enter_time.php?uid=" . $userid . "?action=timesubmit' method='post'>";
You have a quote after uid that should not be there:
"<form action='enter_time.php?uid=" . $userid . "?action=timesubmit method='get'>";
If you are using a form to submit GET variables into a url you could do something like
<a id="submit_time<?= $time_cell_row . $time_cell_column ?>" href="enter_time.php?uid=<?= $userid ?>">Submit Time</a>
If you prefer to use a form, writing it this way looks clearer to me
PHP
<?php
$getuserid_result = mysql_query($getuseridsql, $conn);
$userid_array = mysql_fetch_array($getuserid_result);
$userid = $userid_array['uid'];
// Above code works fine and retrieves the current user's ID
// PHP Form code is below
// Variables used for creating the id of the input since the submit button is displayed
// in an HTML table with multiple rows. These variables are working fine.
$time_cell_row = 1;
$time_cell_column = 1;
?>
<form action='enter_time.php' method='get'>
<input type="hidden" name="action" value="<?= $timesubmit ?>">
<input type="hidden" name="uid" value="<?= userid ?>">
<input name="submit_time" type="submit" id="submit_time<?= $time_cell_row . $time_cell_column ?>" />
</form>
<?php
// PHP Action code
/* This is currently commented out and will eventually be filled with code to handle
the 'timesubmit' action
if (isset($_GET['action'])) {
switch (strtolower($_GET['action'])) {
case 'timesubmit':
}
}
*/
?>
Just off top of my head it should be:
echo "<form action='enter_time.php?uid=" . $userid . "?action=timesubmit' method='get'>";
Single quote after "uid=" was in the wrong place. Shouldn't be until after "timesubmit".
I have this form that contains dynamically generated textboxes filled with values (those are read from the database), and I let the user modify and save them.
But I don't know how to save the data, how to pass them to the "saver" php page (which eventually the same now, doesn't matter...)
For now, they seem like this:
echo "<td><input type=\"text\" id=\"category$category_id\" name=\"category$category_id\" value=\"$category_sequence\" style=\"width: 25px;\" /></td>";
What should be the "name" in this side, and how to reach them from the $_POST on the other side?
In PHP, take a look what you have from your form so far:
<?php
print_r($_POST);
?>
This code will show you what you have. Then you can access any field by its name:
<?php
$variable = $_POST['field_name'];
?>
Be sure to check if there is any POST data was sent:
<?php
if (isset($_POST) && is_array($_POST))
{
// ...
}
?>
Be sure that you have needed field sent by POST form:
<?php
$variable = (array_key_exists('field_name', $_POST) ? $_POST['field_name'] : '');
?>
Finally I got results.
I should use this way:
print "<input type="text" name="cat[]" value="$category_sequence" />"
Then an array ($_POST['cat']) will be created I can iterate through.
Or:
print "<input type="text" name="cat[$catId]" value="$category_sequence" />"
Again, iteration.
On the server side, if I stay on my original idea:
$i=1;
while(isset($_POST['cat'.$i]))
{
print "There is "cat".$i item, it is processable."
$i++;
}
All I wanted was this... thank you.
I can't think of an easy way to explain what I'm trying to accomplish..
Inserting data into MySQL using php is simple, yet I need to be able to give users the option to add more text inputs in one form...
Just for example purpose...
Users can create a shopping list, the page loads with 15 inputs for 15 items they wish to insert into their shopping list...
At the bottom, they can have the option to add another item, and when clicked, it will show an additional text input..
I've looked for examples but off the top of my head I can't think of any...
if(isset($_POST['createList']){
$item=addslashes(strip_tags($_POST['item']));
}
mysqli_query("INSERT INTO shoppingLists (id,itemName) VALUES (``,`$item`)");
How do insert multiple items with a simple POST?
I was hoping it's possible to use JQuery to add additional input fields.. but how is something like this accomplished on the PHP side?
I do hope I've explained this well enough haha.
You can use an array for your input name attribute
<input type="text" name="item[]" />
And you can browse it by looping through your variable $_POST['item'], that now contains an array with an entry for each field in your form.
I use jQuery .clone() for this.
html:
<div id=="ShoppingList">
<input class="item" name="item[]" />
<input type="button" onclick="addAnotherItem()" />
</div>
js:
function addAnotherItem(){
$("#ShoppingList input.item:first").clone().val("").appendTo("#ShoppingList");
}
I use .val("") so that whatever value the first input has isn't copied to the new one.
Sample Code For This inserting multiple images
if(isset($_POST['addSpace'])){
$spaceTitle = mysql_real_escape_string($_POST['title']);
$spaceBody = mysql_real_escape_string($_POST['text']);
if($_FILES['SliderImage']['tmp_name'] != "" ){
if (($_FILES["SliderImage"]["type"] == "image/jpeg")
&& ($_FILES["SliderImage"]["size"] < 2000000))
{
if ($_FILES["SliderImage"]["error"] > 0)
{
echo "<div class='error_box'><p>Error :: " . $_FILES["SliderImage"]["error"] . ".</p></div>'";
}else{
$path = "../images/prisma-img/demo/services/";
$path2 = "images/prisma-img/demo/services/";
$num = mt_rand();
if (file_exists($path . $num.".jpg" ))
{
echo "<div class='error_box'>"."(".$num .")".
" already exists. "."</div>";
}else{
if(move_uploaded_file($_FILES["SliderImage"]["tmp_name"],$path . $num.".jpg" )){
$mysqlPath = $path2. $num.".jpg" ;
$result = $db->insert("pages","pageTitle, pageImage, pageBody, pageSlug ", "'$spaceTitle','$mysqlPath','$spaceBody','services'");
if($db->affected_rows()){
$id=mysql_insert_id();
echo '<div class="valid_box"><p>Success :: Services successfully Added.</p></div>';
echo "<meta http-equiv='refresh' content='1; url= add-services-slide.php?id=".$id."' />";
}
}
}
}
}else{
echo '<div class="error_box"><p>Error :: Only JPEG file allowed.</p></div>';
}
}
}
?>
Hope that this will help u.